原生javascript操作select下拉選單程式碼例項

antzone發表於2017-03-17

本章節以程式碼段的形式介紹一下原生的javascript如何操作select,從建立下拉選單到刪除下來選單,還有新增或者刪除option項都一一列舉,對於初學者或者不熟悉相關操作可能會有所幫助。

一.建立select下拉選單:

[JavaScript] 純文字檢視 複製程式碼
function createSelect(){ 
  var selectObj=document.createElement("select"); 
  selectObj.id="sel"; 
  document.body.appendChild(selectObj); 
}

以上程式碼可以建立一個select下拉選單,並設定它的id屬性值,最後新增到body中。

二.為select下拉選單新增option項:

[JavaScript] 純文字檢視 複製程式碼
function removeAll(){ 
  var selectObj=document.getElementById('sel'); 
  selectObj.options.length=0; 
}

以上程式碼會為selext下拉選單追加一個option項。

三.刪除所有的option選項:

[JavaScript] 純文字檢視 複製程式碼
function removeAll(){ 
  var selectObj=document.getElementById('sel'); 
  selectObj.options.length=0; 
}

以上程式碼可以刪除所有的option選項。

四.刪除指定索引的option項:

[JavaScript] 純文字檢視 複製程式碼
function removeOne(){ 
  var selectObj=document.getElementById('sel'); 
  //index,要刪除選項的序號,這裡取當前選中選項的序號 
  var index=selectObj.selectedIndex; 
  selectObj.options.remove(index); 
}

以上程式碼可以將選中項刪除,索引值是從0開始的。

五.獲得指定option項的value值:

[JavaScript] 純文字檢視 複製程式碼
var selectObj=document.getElementById('sel'); 
var index=selectObj.selectedIndex; //序號,取當前選中選項的序號 
var val=selectObj.options[index].value;

以上程式碼可以獲取選中option項的value屬性值。

六.獲得指定option項的text文字內容:

[JavaScript] 純文字檢視 複製程式碼
var selectObj=document.getElementById('sel'); 
var index=selectObj.selectedIndex; //序號,取當前選中選項的序號 
var text=selectObj.options[index].text;

七.修改option的相關內容:

[JavaScript] 純文字檢視 複製程式碼
var selectObj=document.getElementById('sel'); 
var index=selectObj.selectedIndex;//序號,取當前選中選項的序號 
selectObj.options[index]=new Option("新文字","新值");

八.刪除select下拉選單:

[JavaScript] 純文字檢視 複製程式碼
function removeSelect()
{ 
  var selectObj=document.getElementById("sel"); 
  selectObj.parentNode.removeChild(selectObj); 
}

相關文章