JavaScript - 使用数组填充下拉列表
问题描述:
我在脚本中声明了一个数组:
I have an array declared in a script:
var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
我有一个包含下拉菜单的表格:
I have a form which contains a drop down menu:
<form id="myForm">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</form>
使用Javascript,如何使用数组值填充下拉菜单的其余部分?这样选项将是选择一个数字,1,2,3,4,5。 。 。 。 。 N?
Using Javascript, how will I populate the rest of the drop down menu with the array values? So that the options will be "Choose a number", "1", "2", "3", "4", "5" . . . . . "N"?
答
您需要遍历数组元素,为每个元素创建一个新的DOM节点并附加它你的对象。
You'll need to loop through your array elements, create a new DOM node for each and append it to your object.
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}