如何以编程方式添加下拉列表 (<select>)? [英] How to add Drop-Down list (<select>) programmatically?
本文介绍了如何以编程方式添加下拉列表 (<select>)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个函数,以便以编程方式在页面上添加一些元素.
I want to create a function in order to programmatically add some elements on a page.
假设我想添加一个带有四个选项的下拉列表:
Lets say I want to add a drop-down list with four options:
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
我该怎么做?
推荐答案
这会起作用(纯 JS,附加到 id myDiv
的 div):
This will work (pure JS, appending to a div of id myDiv
):
var myParent = document.body;
//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
这篇关于如何以编程方式添加下拉列表 (<select>)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文