0

我正在尝试以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完成后,以某种方式关闭`并开始一个新的。

有任何想法吗?

4

2 回答 2

1

试试这个:http: //jsfiddle.net/qaczD/2/

// populate <select> with available choices
$.getJSON('http://dl.dropboxusercontent.com/u/48552248/websites/timewasted/new/industries.json', function (data) {
    $.each(data.sectors, function (i, sector) {
        $.each(sector.subsectors, function (i, subsector) {

             var optGroup=$('<optgroup />').attr('label','#' + subsector.title).appendTo('.js-industries-select');
            $.each(subsector.industries, function (i, industry) {
                // if (industry.name.search(regex) != -1) {
                    $(optGroup).append( $('<option />').html(industry.name));
                // }
            })
        });
    });
    console.log('yes');
});

// call chosen plugin that prettifies the Industry options
setTimeout(function() {$(".js-industries-select").chosen({
  placeholder_text_multiple: 'e.g. Retail banking…'
});}, 1000);
于 2013-11-14T09:19:40.023 回答
1

解决方案

 $.each(sector.subsectors, function (i, subsector) {
        var group = $('<optgroup />').attr('label','#' + subsector.title).appendTo('.js-industries-select');

        $.each(subsector.industries, function (i, industry) {
            $('<option />').html(industry.name).appendTo(group);
        })
    });
于 2013-11-14T09:19:45.770 回答