如何在 select 选项中使用 'for each'?

How using 'for each' in select option?

我想问一下每一个 这是我的 HTML

<select class="namaKota" id="fromCity"></select>

我在 js 中的数据

var listCity =
  {
    "Popular":
    [
       {"cityname":"London","code":"LDN"},
       {"cityname":"Rome","code":"ROM"},
       {"cityname":"Madrid","code":"MDR"}
    ],
     "Germany":
    [
       {"cityname":"Hamburg", "code":"HMB"},
       {"cityname":"Frankfurt", "code":"FRN"}
     ]
}

这是我的 JS

var a = $("select#fromCity").val();
listKota.forEach(function(e){
   a.append('<option value="'+ listCity.code +'">'+ listCity.cityname +'</option>');});

我想成为这个形象。如何为每个创建 using?

这是我的 jsfiddle。 https://jsfiddle.net/dedi_wibisono17/9u9uec8d/1/有人帮忙吗?谢谢

您图片中的布局使用 <optgroup> 元素对 <option> 进行分组。因此你需要两个循环;一个从对象的键创建 optgroups,另一个在这些组中填充实际的 option。试试这个:

var listCity = {
  "Popular": [
    { "cityname": "London", "code": "LDN" },
    { "cityname": "Rome", "code": "ROM" },
    { "cityname": "Madrid", "code": "MDR" }
  ],
  "Germany": [
    { "cityname": "Hamburg", "code": "HMB" },
    { "cityname": "Frankfurt", "code": "FRN" }
  ]
}

Object.keys(listCity).forEach(function(key) {
  var $group = $('<optgroup label="' + key + '"></optgroup>');

  listCity[key].forEach(function(obj) {
    $group.append('<option value="' + obj.code + '">' + obj.cityname + '</option>')
  })

  $('#fromCity').append($group);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="fromCity"></select>

您需要创建 optGroup 元素,其中 option 元素需要添加 select 元素。

var select = $("select#fromCity");

//Iterate list City
for (var key in listCity) {
    var cities = listCity[key];

    //Create optGroup
    var optGroup = $('<optgroup/>', {
        label: key 
    })
    for (var i = 0; i < cities.length; i++) {
        //Create option and append to optGroup created above
        $('<option>', {
            value: cities[i].code,
            text: cities[i].cityname,
        }).appendTo(optGroup);
    }

    optGroup.appendTo(select);
}

var listCity = {
  "Popular": [
    { "cityname": "London", "code": "LDN" },
    { "cityname": "Rome", "code": "ROM" },
    { "cityname": "Madrid", "code": "MDR" }
  ],
  "Germany": [
    { "cityname": "Hamburg", "code": "HMB" },
    { "cityname": "Frankfurt", "code": "FRN" }
  ]
}

var select = $("select#fromCity");

//Iterate list City
for (var key in listCity) {
  var cities = listCity[key];

  //Create optGroup
  var optGroup = $('<optgroup/>', {
    label: key
  })
  for (var i = 0; i < cities.length; i++) {
    //Create option and append to optGroup created above
    $('<option>', {
      value: cities[i].code,
      text: cities[i].cityname,
    }).appendTo(optGroup);
  }

  optGroup.appendTo(select);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="fromCity"></select>

Updated Fiddle