从json创建下拉列表 [英] create drop down list from json
问题描述
我有一个这样的json:
I have a json in this form:
{"COLUMNS":["ID", "Name"],"DATA":
[
["1","Joe"],
["2", "Sam"],
["3", "Doug"],
]
}
我正在寻找一个如何从javascript中的这个数据创建一个下拉列表,但所有的json /下拉列表的例子列出了json是不同的格式。我还没有使用javascript很多或者json数据,所以我不知道从哪里开始。任何人都可以指出一个伟大的教程或例子的方向吗?谢谢。
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:
The 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);
};
};
请确保如果您的JSON是字符串形式,那么您首先使用 JSON.parse();
Please make sure that if your JSON is in string form, that you parse it first using JSON.parse();
HTML:
<select id="selector"></select>
JSFiddle示例: http://jsfiddle.net/su7sr/1
The JSFiddle Example: http://jsfiddle.net/su7sr/1
这篇关于从json创建下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!