使用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 = $('#mySelect').get(0).options;
$.each(selectValues, function(key, value) {
        options[options.length] = new Option(value, key);
});

这是完全跨浏览器兼容的。

其他回答

<!DOCTYPE html>
<html lang="en">
<head>
  <title>append selectbox using jquery</title>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <script type="text/javascript">
    function setprice(){
        var selectValues = { "1": "test 1", "2": "test 2" };
        $.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value",key)
                    .text(value)); 
});

    }
  </script>
</head>
<body onload="setprice();">


      <select class="form-control" id="mySelect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
  </select>


</body>
</html>

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

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

我决定插嘴。

处理先前选择的选项;当我们附加仅使用追加命中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

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

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

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

附加它,

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

甚至更好

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