使用jQuery从JavaScript对象向<select>添加选项的最佳方法是什么?

我正在寻找一些不需要插件的东西,但我也会对现有的插件感兴趣。

这是我所做的:

selectValues = { "1": "test 1", "2": "test 2" };

for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
  }
}

干净/简单的解决方案:

这是matdumsa的清理和简化版本:

$.each(selectValues, function(key, value) {
     $('#mySelect')
          .append($('<option>', { value : key })
          .text(value));
});

matdumsa的更改:(1)删除了append()内选项的close标记,(2)将财产/属性作为append)的第二个参数移动到映射中。


当前回答

我做了类似的事情,通过Ajax加载一个下拉项。上面的响应也是可以接受的,但是为了更好的性能,尽可能少地修改DOM总是很好的。

因此,与其在循环中添加每个项目,不如在循环中收集项目,并在完成后将其追加。

$(data).each(function(){
    ... Collect items
})

附加它,

$('#select_id').append(items); 

甚至更好

$('#select_id').html(items);

其他回答

我发现这很简单,效果很好。

for (var i = 0; i < array.length; i++) {
    $('#clientsList').append($("<option></option>").text(array[i].ClientName).val(array[i].ID));
};

对老@joshberry的回答进行了改进:

看起来plain.append也能像预期的那样工作,

$("#mySelect").append(
  $.map(selectValues, function(v,k){

    return $("<option>").val(k).text(v);
  })
);

或更短,

$("#mySelect").append(
  $.map(selectValues, (v,k) => $("<option>").val(k).text(v))
  // $.map(selectValues, (v,k) => new Option(v, k)) // using plain JS
);
function populateDropdown(select, data) {   
    select.html('');   
    $.each(data, function(id, option) {   
        select.append($('<option></option>').val(option.value).html(option.name));   
    });          
}   

它与jQuery1.4.1配合得很好。

有关在ASP.NET MVC和jQuery中使用动态列表的完整文章,请访问:

使用MVC和jQuery的动态选择列表

尽管前面的答案都是有效的答案,但最好先将所有这些附加到documentFragmnet,然后将该文档片段作为元素附加到。。。

看看约翰·雷格对此事的看法。。。

大致如下:

var frag = document.createDocumentFragment();

for(item in data.Events)
{
    var option = document.createElement("option");

    option.setAttribute("value", data.Events[item].Key);
    option.innerText = data.Events[item].Value;

    frag.appendChild(option);
}
eventDrop.empty();
eventDrop.append(frag);

如果您不必支持旧的IE版本,那么使用Option构造函数显然是一种可读且高效的解决方案:

$(new Option('myText', 'val')).appendTo('#mySelect');

它的功能等同于,但比:

$("<option></option>").attr("value", "val").text("myText")).appendTo('#mySelect');