简体   繁体   English

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

[英]How to create HTML select option from JSON hash?

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>

Try this. 尝试这个。

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

Create option element and then use append method to append them into select element. 创建option元素,然后使用append方法将它们附加到select元素中。

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

Demo 演示

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>

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]) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM