我正在尝试以subsectorsJSON 显示在一个中的方式解析 JSON 文件<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/
我基本上需要<optgroup>在 last 之前创建一个$.each,分配label=""assubsector.title然后用选项填充该组。最后一个$.each完成后,以某种方式关闭`并开始一个新的。
有任何想法吗?