使用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);

其他回答

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

我决定插嘴。

处理先前选择的选项;当我们附加仅使用追加命中DOM一次添加更多选项时处理多个属性演示如何使用对象演示如何使用对象数组进行映射

//对象作为值/desc让selectValues={“1”:“测试1”,“2”:“测试2”,“3”:“测试3”,“4”:“测试四”};//在这里使用div,因为使用“select”会破坏“mySelect”中的原始选定值let opts=$(“<div/>”);让opt={};$.each(选择值,函数(值,描述){opts.append($('<option/>').prop(“value”,value).text(desc));});opts.find(“option”).appendTo('#mySelect');//对象中称为“选项”的对象数组让selectValuesNew={选项:[{值:“1”,description:“2测试1”},{值:“2”,description:“2测试2”,选定:真},{值:“3”,description:“2测试3”},{值:“4”,description:“2测试四”}]};//在这里使用div,因为使用“select”会破坏原始选定值让opts2=$(“<div/>”);让opt2={}//仅在添加所有选项后追加$.map(selectValuesNew.options,函数(val,索引){opts2.append($('<option/>').prop(“值”,val.value).prop(“选定”,值选定).text(值描述));});opts2.find(“option”).appendTo(“#mySelectNew”);<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><select id=“mySelect”><option value=“”selected=“selected”>空</option></选择><select id=“mySelectNew”multiple=“multiple”><option value=“”selected=“selected”>2空</option></选择>

将HTML选择id设置为以下行。在这里,mySelect用作select元素的id。

   var options = $("#mySelect");

然后获取这个场景中的selectValues对象,并将其设置为每个循环的jquery。它将相应地使用对象的值和文本,并将其附加到选项选择中,如下所示。

$.each(selectValues, function(val, text) {
            options.append(
             $('<option></option>').val(val).html(text)
          );
      });

当选择下拉列表时,这将显示文本作为选项列表,一旦选择文本,将使用所选文本的值。

Eg.

“1”:“测试1”,“2”:“测试2”,

下拉列表,

显示名称:测试1->值为1显示名称:测试2->值为2

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一次。

这稍微更快更干净。

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>