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


当前回答

被警告。。。我在Android 2.2(Cyanogen 7.0.1)手机(T-Mobile G2)上使用jQuery Mobile 1.0b2和PhoneGap 1.0.0,根本无法使用.append()方法。我不得不像下面这样使用.html():

var options;
$.each(data, function(index, object) {
    options += '<option value="' + object.id + '">' + object.stop + '</option>';
});

$('#selectMenu').html(options);

其他回答

获取对象键以获取对象值。使用map()添加新选项。

常量选择值={“1”:“测试1”,“2”:“测试2”}const selectTest=document.getElementById('selectTest')Object.keys(selectValues).map(key=>selectTest.add(新选项(selectValues[key],key)))<select id=“selectTest”></select>

JSON格式:

[{
    "org_name": "Asset Management"
}, {
    "org_name": "Debt Equity Foreign services"
}, {
    "org_name": "Credit Services"
}]

以及jQuery代码,用于填充Ajax成功时下拉列表的值:

success: function(json) {
    var options = [];
    $('#org_category').html('');  // Set the Dropdown as Blank before new Data
    options.push('<option>-- Select Category --</option>');
    $.each(JSON.parse(json), function(i, item) {
        options.push($('<option/>',
        {
           value: item.org_name, text: item.org_name
        }));
    });
    $('#org_category').append(options);  // Set the Values to Dropdown
}

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

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

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

附加它,

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

甚至更好

$('#select_id').html(items);
$.each(selectValues, function(key, value) {
    $('#mySelect').append($("<option/>", {
        value: key, text: value
    }));
});
if (data.length != 0) {
    var opts = "";
    for (i in data)
        opts += "<option value='"+data[i][value]+"'>"+data[i][text]+"</option>";

    $("#myselect").empty().append(opts);
}

这只在第一次构建一个巨大字符串后操纵DOM一次。