Javascript 如何从 JSON 哈希创建 HTML 选择选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9071525/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:34:15  来源:igfitidea点击:

How to create HTML select option from JSON hash?

javascriptjqueryjsonoption

提问by netdjw

I have a simple JSON code:

我有一个简单的 JSON 代码:

[{'1':'Name'}, {'2', 'Age'}, {'3','Gender'}]

I have a select tag in my HTML:

我的 HTML 中有一个 select 标签:

<select name="datas" id="datas"></select>

I need a simple way to create HTML select box from this JSON, like this:

我需要一种简单的方法来从此 JSON 创建 HTML 选择框,如下所示:

<select name="datas" id="datas">
    <option value="1">Name</option>
    <option value="2">Age</option>
    <option value="3">Gender</option>
</select>

回答by ShankarSangoli

Try this.

尝试这个。

//Correct(missing colons) in the array items
var data = [{'1':'Name'}, {'2': 'Age'}, {'3': 'Gender'}];

Create optionelement and then use appendmethod to append them into select element.

创建option元素,然后使用append方法将它们附加到选择元素中。

var $select = $('#datas');
$.each(data, function(i, val){
    $select.append($('<option />', { value: (i+1), text: val[i+1] }));
});

Demo

演示

回答by Michal

Just for kicks here is an answer in pure javascript, also you probably do not need an array for this just a simple object will suffice

只是为了踢这里是纯 javascript 中的答案,你可能也不需要一个数组,一个简单的对象就足够了

    <select name="datas" id="datas"></select>
    <script>

        html = "";
        obj = {
            "1" : "Name",
            "2": "Age",
            "3" : "Gender"
        }
        for(var key in obj) {
            html += "<option value=" + key  + ">" +obj[key] + "</option>"
        }
        document.getElementById("datas").innerHTML = html;

    </script>

回答by steviethecat

The above answer assumes that the data indexes of the array are in order. What if the data variable would be:

上面的答案假设数组的数据索引是有序的。如果数据变量是:

var data = [ {'23':'Age'}, {'12':'Gender'}, {'3':'Name'}];

So in alphabetical order, but with random id's.

因此按字母顺序排列,但使用随机 ID。

One way I found in solving this is:

我发现解决这个问题的一种方法是:

$.each(data, function(key, value) {
  var i = Object.keys(value)[0];
  $("select#datas").append( $("<option />").val(i).text(value[i]) );