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


当前回答

这里可以找到jQuery插件:使用jQuery和AJAX自动填充选择框。

其他回答

简单的方法是:

$('#SelectId').html("<option value='0'>select</option><option value='1'>Laguna</option>");

尽管前面的答案都是有效的答案,但最好先将所有这些附加到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);
 $.each(response, function (index,value) {
                        $('#unit')
                            .append($("<option></option>")
                                .attr("value", value.id)
                                .text(value.title));
                    });

被警告。。。我在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);

由于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'));