javascript 从 json 创建下拉列表

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

create drop down list from json

javascriptjsondrop-down-menu

提问by user2533762

I have a json in this form:

我有一个这种形式的json:

{"COLUMNS":["ID", "Name"],"DATA":
[ 
  ["1","Joe"],
  ["2", "Sam"],
  ["3", "Doug"],
]
}

and I was looking for an example of how to create a drop down list from this data in javascript but all the examples of json/dropdown list the json is in a different format. I haven't worked with javascript much or json data at all so I'm not sure about where to start. Can anyone point me in the direction of a great tutorial or examples? Thanks.

我正在寻找一个示例,说明如何在 javascript 中根据此数据创建下拉列表,但是 json/下拉列表的所有示例 json 的格式不同。我根本没有使用过 javascript 或 json 数据,所以我不确定从哪里开始。任何人都可以为我指出一个很棒的教程或示例的方向吗?谢谢。

采纳答案by Shawn31313

The JavaScript:

JavaScript:

window.onload = function () {
    var JSON = {
        "COLUMNS":["ID", "Name"],
        "DATA": [ 
            ["1","Joe"],
            ["2", "Sam"],
            ["3", "Doug"]
        ]
    }, select = document.getElementById("selector");
    for (var i = 0, at = JSON.DATA[i], id = at[0], name = at[1]; i < JSON.DATA.length; i++) {
        var option = document.createElement("option");
        option.value = id;
        option.textContent = name;
        select.appendChild(option);
    };
};

Please make sure that if your JSON is in string form, that you parse it first using JSON.parse();

请确保如果您的 JSON 是字符串形式,您首先使用 JSON.parse();

The HTML:

HTML:

<select id="selector"></select>

The JSFiddle Example: http://jsfiddle.net/su7sr/1

JSFiddle 示例:http: //jsfiddle.net/su7sr/1

回答by user2935683

I thing that correct JS will be:

我认为正确的 JS 将是:

window.onload = function () {
    var JSON = {
        "COLUMNS":["ID", "Name"],
        "DATA": [ 
            ["1","Joe"],
            ["2", "Sam"],
            ["3", "Doug"]
        ]
    }, select = document.getElementById("selector");
    for (var i = 0; i < JSON.DATA.length; i++) {
    var at = JSON.DATA[i], id = at[0], name = at[1];
        var option = document.createElement("option");
        option.value = id;
        option.textContent = name;
        select.appendChild(option);
    };
};