使用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)的第二个参数移动到映射中。


当前回答

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

其他回答

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

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

这稍微更快更干净。

var选择值={“1”:“测试1”,“2”:“测试2”};var$mySelect=$('#mySelect');//$.each(选择值、功能(键、值){var$option=$(“<option/>”{value:键,文本:值});$mySelect.append($option);});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><select id=“mySelect”></select>

这个解决方案在Chrome中存在排序问题(jQuery 1.7.1)(Chrome按名称/编号对对象财产进行排序?)所以为了保持秩序(是的,这是滥用对象),我改变了这个:

optionValues0 = {"4321": "option 1", "1234": "option 2"};

到此为止

optionValues0 = {"1": {id: "4321", value: "option 1"}, "2": {id: "1234", value: "option 2"}};

然后每个$.看起来像:

$.each(optionValues0, function(order, object) {
  key = object.id;
  value = object.value;
  $('#mySelect').append($('<option>', { value : key }).text(value));
}); 

使用$.map()函数,可以以更优雅的方式执行此操作:

$('#mySelect').html( $.map(selectValues, function(val, key){
    return '<option value="' + val + '">'+ key + '</option>';
}).join(''));

尽管前面的答案都是有效的答案,但最好先将所有这些附加到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);