如何使用 JavaScript 使用键/值声明和初始化数组,然后动态创建选择下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5435347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare and initialize an array with key/values using JavaScript and then dynamically creating select dropdown
提问by Karim Ali
How to declare and initialize an array with key/values using JavaScript and then dynamically creating select dropdown and assigning key/values to the options using JavaScript?
如何使用 JavaScript 使用键/值声明和初始化数组,然后使用 JavaScript 动态创建选择下拉列表并将键/值分配给选项?
Thanks
谢谢
回答by Hari Gangadharan
It would be easier if you use JQuery... This is how it would be done in basic Javascript.
如果您使用 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>
回答by AlanFoster
You're not looking for an array for this, you should use an object, for instance :
你不是在为此寻找一个数组,你应该使用一个对象,例如:
var list = {"some option": 1, "another option": 2, "etc": 3};
To therefore insert these to a dropdown you could append it to an existing option list by doing
因此,要将这些插入到下拉列表中,您可以通过执行以下操作将其附加到现有选项列表中
for(var optionText in options) {
var option = new Option(optionText, options[listText], true, false)
document.getElementById("listName").options.add(option)
}
Combined the code may look something like :
组合后的代码可能类似于:
<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>
I hope that helps, it should be more than enough for you to get started.
我希望这会有所帮助,它应该足以让您入门。
Edit : You should obviously note that doing window.onload and replacing it with a function like that may cause undesired effects if you have existing code, so either make use of your existing library's loaded functions etc
编辑:您显然应该注意,如果您有现有代码,则执行 window.onload 并将其替换为类似的函数可能会导致不良影响,因此请使用现有库的加载函数等