使用 JavaScript 数组填充下拉选择框

use a javascript array to fill up a drop down select box

本文关键字:选择 填充 JavaScript 数组 使用      更新时间:2023-09-26

我有一个文本文件,我正在读取并将数据存储在javascript数组中,它是一个美食列表。我想使用数组来填充下拉选择框。我知道如何在下拉框的值中进行硬编码(如果我错了,请使用纠正我),但我希望能够使用数组来填充它。

<script type="text/javascript">
var cuisines = ["Chinese","Indian"];            
</script>
<select id="CusineList"></select>

为了简单起见,我硬编码了一个数组,"美食列表"是我的下拉框

使用 for 循环遍历数组。对于每个字符串,创建一个新的 option 元素,将该字符串指定为其innerHTMLvalue,然后将其追加到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);
}

演示

更新:使用createDocumentFragmentforEach

如果要追加到文档的元素列表非常大,则单独追加每个新元素可能性能不佳。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);

演示

这是我最近写的REST-Service的一部分。

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() 在我的情况下不起作用,所以我决定提出另一种也有效的可能性。