如何使用<option>原版JS从.json文件创建条目列表?



我需要从一个包含键和值的.json文件中创建HTML表单条目列表。获取文件等没有问题。整天都在与循环作斗争,但似乎什么都不起作用。这是我的.json文件的一部分:

{
"City": "0",
"Another City": "1",
"Yet Another City": "2",
(...)
}

这就是我想在HTML中实现的(例如,通过innerHTML添加选项(:

<option id="0">City</option>
<option id="1">Another City</option>
<option id="2">Yet Another City</option>
(...)

我正在尝试循环并使用Object.keys(ObjectVariableName([0],但无法使其工作。我将感谢你的帮助。

您需要创建option元素,设置每个元素的textvalue,然后将它们附加到select:

let obj = {
"City": "0",
"Another City": "1",
"Yet Another City": "2",
}
let select = document.getElementById("myList");
for (var key in obj) {
var option = document.createElement("option");
option.text = key;
option.value = obj[key];
select.add(option);
}
console.log(select.innerHTML);
<select id="myList"></select>

使用add((和new option((方法

const  mySelect = document.getElementById('my-select')
,    data = 
{ 'City': '0'
, 'Another City': '1'
, 'Yet Another City': '2'
}
;
for (const [key, value] of Object.entries(data))
{
mySelect.add(new Option(key, value))     
}
console.log(mySelect.innerHTML);
<select name="xxx" id="my-select"></select>

最新更新