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


当前回答

还有一种方法:

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

其他回答

还有一种方法:

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

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

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

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

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

jQuery

var list = $("#selectList");
$.each(items, function(index, item) {
  list.append(new Option(item.text, item.value));
});

香草JavaScript

var list = document.getElementById("selectList");
for(var i in items) {
  list.add(new Option(items[i].text, items[i].value));
}

由于JQuery的append可以将数组作为参数,所以我很惊讶没有人建议将其与map一起使用

$('#the_select').append(['a','b','c'].map(x => $('<option>').text(x)));

或减少

['a','b','c'].reduce((s,x) => s.append($('<option>').text(x)), $('#the_select'));