【发布时间】:2013-11-14 09:13:23
【问题描述】:
我正在尝试解析 JSON 文件,使 JSON 的 subsectors 显示在 <optgroup label=""> 中(不希望它们是可选的)。
我有这个 JSON 文件:
{
"sectors": [
{
"title": "Business, Finance & Technology",
"subsectors": [
{
"title": "Finance and insurance",
"industries": [
{"name": "Retail banking"},
{"name": "Insurance"},
{"name": "Investment banking"}
]
},
{
"title": "Business Services",
"industries": [
{"name": "Accounting & Audit"},
{"name": "Recruitment"},
{"name": "Legal services"}
]
}
]
},
// extra code omitted for brevity
我用这个填充<select> 选项:
// populate <select> with available choices
$.getJSON('models/industries.json', function (data) {
$.each(data.sectors, function (i, sector) {
$.each(sector.subsectors, function (i, subsector) {
$('<option />').html('#' + subsector.title).appendTo('.js-industries-select');
$.each(subsector.industries, function (i, industry) {
$('<option />').html(industry.name).appendTo('.js-industries-select');
})
});
});
});
然后我调用 Chosen 插件将<select> 更改为动态输入。你可以看到我想要哪些元素为label 被标记为#。
在此处查看演示:http://jsfiddle.net/qaczD/
我基本上需要在最后一个$.each 之前创建一个<optgroup>,将label="" 分配为subsector.title,然后用选项填充该组。完成最后一个 $.each 后,以某种方式关闭 ` 并开始一个新的。
有什么想法吗?
【问题讨论】:
-
@ArunPJohny 谢谢,你真棒!
标签: javascript jquery json loops optgroup