如何使用JavaScript声明和初始化具有键/值的数组,然后动态创建选择下拉列表并使用JavaScript为选项分配键/值?
谢谢
Har*_*ran 10
如果你使用JQuery会更容易......这就是它在基本的Javascript中的表现.
<html>
<body>
<span id="selectContainer"></span>
</body>
<script type="text/javascript">
var selectItems = {
me: "Hari Gangadharan",
friend1: "Asif Aktar",
friend2: "Jay Thomas",
friend3: "John Abrams"
}
selectItems["newFriend"] = "Niel Goldman";
var selectContainer = document.getElementById("selectContainer");
var selectBox = document.createElement("SELECT");
selectBox.id = selectBox.name = "friendList";
selectContainer.appendChild(selectBox);
for (var key in selectItems) {
var value = selectItems[key];
var option = document.createElement("OPTION");
option.text = value;
option.value = key;
selectBox.options.add(option);
}
</script>
</html>
Run Code Online (Sandbox Code Playgroud)
你不是在寻找一个数组,你应该使用一个对象,例如:
var list = {"some option": 1, "another option": 2, "etc": 3};
Run Code Online (Sandbox Code Playgroud)
因此,要将这些插入到下拉列表中,您可以通过执行将其附加到现有选项列表
for(var optionText in options) {
var option = new Option(optionText, options[listText], true, false)
document.getElementById("listName").options.add(option)
}
Run Code Online (Sandbox Code Playgroud)
结合代码可能看起来像:
<script type="text/javascript">
var options = {"some option": 1, "another option": 2, "etc": 3};
window.onload = function() {
for(var optionText in options) {
var option = new Option(optionText, options[listText], true, false)
document.getElementById("listName").options.add(option)
}
}
</script>
<select id="listName">
</select>
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助,它应该足以让你开始.
编辑:您应该注意到,如果您有现有代码,执行window.onload并将其替换为类似函数可能会导致不良影响,因此要么使用现有库的加载函数等
| 归档时间: |
|
| 查看次数: |
55172 次 |
| 最近记录: |