<optgroup> с JSON в цикле $ .each

0

Im пытается разобрать JSON файл таким образом, что subsectors 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> до последнего $.each, назначить label="" как subsector.title а затем заполнить эту группу вариантами. Как только $.each последний $.each, закройте "как-то" и запустите новый.

Есть идеи?

  • 1
    см. jsfiddle.net/arunpjohny/LH38A/1
  • 0
    @ArunPJohny спасибо, ты молодец!
Теги:
loops
optgroup

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);
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);
        })
    });

Ещё вопросы

Сообщество Overcoder
Наверх
Меню