JavaScript 動態生成select下拉選單

admin發表於2017-12-04

在實際應用中,可能需要動態生成select下拉選單,本章節通過程式碼例項介紹一下如何實現此功能。

程式碼如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript"> 
function setFun(){ 
  var id = new Array(1,2,3); 
  var value = new Array("JavaScript專區","jQuery專區","例項教程"); 
  var select = document.getElementById("area"); 
  select.length = 1;
  select.options[0].selected = true;
  for(var x = 0;x<id.length;x++){ 
    var option = document.createElement("option"); 
    option.setAttribute("value",id[x]);
    option.appendChild(document.createTextNode(value[x])); 
    select.appendChild(option);
  } 
} 
window.onload=function(){
  setFun()  
}
</script>
</head> 
<body> 
<form> 
<select name="area" id="area"> 
<option value="0">--選擇版塊--</option> 
</select> 
</form> 
</body> 
</html>

可以動態生成select下拉選單,下面簡單介紹一下它的實現過程。

程式碼註釋:

(1).function setFun(){},生成select下拉函式。

(2).var id = new Array(1,2,3),宣告一個陣列並初始化,陣列值是option項的value值。

(3).var value = new Array("javascript專區","jQuery專區","例項教程"),宣告一個陣列並初始化,此陣列的值option的文字內容。

(4).var select = document.getElementById("area"),獲取select物件。

(5).select.length = 1,將select下拉選單的length屬性值設定為1,也就是說只能有一項可以被選中。

(6).select.options[0].selected = true,將第一個option設定為被選項。

(7).for(var x = 0;x<id.length;x++){},使用for迴圈遍歷id陣列。

(8).var option = document.createElement("option"),建立option物件。

(9).option.setAttribute("value",id[x]),將option的value屬性值設定為陣列的對應項。

(10).option.appendChild(document.createTextNode(value[x])),為option項新增文字節點,也就是<option>和</option>之間的文字。

(11).select.appendChild(option),為select下拉選單新增option項。

二.相關閱讀:

(1).document.getElementById參閱document.getElementById()一章節。

(2).document.createElement參閱document.createElement()一章節。

(3).for迴圈參閱JavaScript for 迴圈語句一章節。

(4).setAttribute參閱JavaScript setAttribute()一章節。

(5).appendChild參閱JavaScript appendChild()一章節。

相關文章