【问题标题】:How to create a list of <option> entries from .json file with vanilla JS?如何使用 vanilla JS 从 .json 文件创建 <option> 条目列表?
【发布时间】:2020-11-23 23:25:24
【问题描述】:

我需要从包含键和值的 .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],但无法使其正常工作。 非常感谢您的帮助。

【问题讨论】:

  • 带有循环的 JavaScript 代码在哪里?

标签: javascript html json loops object


【解决方案1】:

你需要创建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);
&lt;select id="myList"&gt;&lt;/select&gt;

【讨论】:

  • 当您知道要枚举的对象时,您不需要obj.hasOwnProperty(key)
【解决方案2】:

使用 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);
&lt;select name="xxx" id="my-select"&gt;&lt;/select&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2021-12-05
    • 2021-06-25
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多