我有一个文本文件,我正在阅读并将数据存储在一个javascript数组中,这是一个美食列表。我想使用数组来填充下拉选择框。我知道如何在下拉框的值中硬编码(如果我错了,请使用正确的我),但我希望能够使用数组填充它。
<script type="text/javascript">
var cuisines = ["Chinese","Indian"];
</script>
<select id="CusineList"></select>
为简单起见,我对数组进行了硬编码,“CuisineList”是我的下拉框
答案 0 :(得分:79)
使用for
循环遍历数组。对于每个字符串,创建一个新的option
元素,将字符串指定为innerHTML
和value
,然后将其附加到select
元素。
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
更新:使用createDocumentFragment
和forEach
如果您要将非常大的元素列表附加到文档,则单独附加每个新元素可能是不合格的。 DocumentFragment
充当轻量级文档对象,可用于收集元素。准备好所有元素后,您可以执行单个appendChild
操作,以便DOM只更新一次,而不是n
次。
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();
cuisines.forEach(function(cuisine, index) {
var opt = document.createElement('option');
opt.innerHTML = cuisine;
opt.value = cuisine;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
答案 1 :(得分:4)
这是我最近写的REST服务的一部分。
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
我发布这个的原因是因为appendChild()在我的情况下不起作用所以我决定提出另一种可行的方法。