【问题标题】:javascript html select add optgroup and option dynamically, how to?javascript html选择动态添加optgroup和选项,如何?
【发布时间】:2020-07-26 16:34:09
【问题描述】:

我有html的内容:

<select name="start" id="start-sel" class="loc">
  <option value="" style="display:none;"></option>
</select>

和javascript内容

$.getJSON('data/locs.json', function(locs) {
  locs.forEach(function(loc) {
    var coords = nodeCoords(loc.node);
    // Skip adding location if node isn't found in getNodes()
    if (!coords) {
      return;
    }
    var newOption = $('<option>').text(loc.name).val(loc.node);
    $('select.loc').append(newOption);
    addLocFlag(nodeCoords(loc.node));
  });
}).then(function() {
  $('select').chosen();
});

$('select#start-sel').change(function() {
  startPicked = true;
  checkStartButton();
  clearMap();
  var node = $('select#start-sel').val();
  addStartFlag(nodeCoords(node));
  zoomMapToFlags();
});

以及 JSON 的内容:

[
  {"name": "Masuk 1", "node": "in1"},
  {"name": "Masuk 2", "node": "in2"},
  {"name": "Masuk 3", "node": "in3"},
  {"name": "Keluar 1", "node": "out1"},
  {"name": "Keluar 2", "node": "out2"},
  {"name": "Keluar 3", "node": "out3"},
  {"name": "Tiket 1", "node": "tick1"},
  {"name": "Tiket 2", "node": "tick2"},
  {"name": "Tiket 3", "node": "tick3"},
]

我已经成功在下拉列表中显示了数据,但是我想用&lt;optgroup&gt;对数据进行分组,怎么办?

【问题讨论】:

  • 你能稍微编辑一下 locs.json 吗?

标签: javascript optgroup


【解决方案1】:

如果你可以编辑locs.json,我会这样做

[
  { "label": "Optgroup 1", "nodes": [ 
    {"name": "Masuk 1", "node": "in1"},
    {"name": "Masuk 2", "node": "in2"},
    {"name": "Masuk 3", "node": "in3"},
  ]},
  { "label": "Optgroup 2", "nodes": [
    {"name": "Keluar 1", "node": "out1"},
    {"name": "Keluar 2", "node": "out2"},
    {"name": "Keluar 3", "node": "out3"},
  ]},
  { "label": "Optgroup 3", "nodes": [
    {"name": "Tiket 1", "node": "tick1"},
    {"name": "Tiket 2", "node": "tick2"},
    {"name": "Tiket 3", "node": "tick3"},
  ]}
]

然后你可以这样做:

$.getJSON('data/locs.json', function(groups) {
  locs.forEach(function(group) {
    var newGroup = $('<optgroup>').attr('label', group.label);
    $('select.loc').append(newGroup);
    group.nodes.forEach(function(loc) {
      var newOption = $('<option>').text(loc.name).val(loc.node);
      newGroup.append(newOption);
    });
    addLocFlag(nodeCoords(loc.node));
  });
}).then(function() {
  $('select').chosen();
});

【讨论】:

  • 抱歉,有一点错误,现在更新。这对你有用吗?
猜你喜欢
  • 2013-08-23
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 1970-01-01
相关资源
最近更新 更多