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

其他回答

我决定插嘴。

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

尽管前面的答案都是有效的答案,但最好先将所有这些附加到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);
<!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>

这个解决方案在Chrome中存在排序问题(jQuery 1.7.1)(Chrome按名称/编号对对象财产进行排序?)所以为了保持秩序(是的,这是滥用对象),我改变了这个:

optionValues0 = {"4321": "option 1", "1234": "option 2"};

到此为止

optionValues0 = {"1": {id: "4321", value: "option 1"}, "2": {id: "1234", value: "option 2"}};

然后每个$.看起来像:

$.each(optionValues0, function(order, object) {
  key = object.id;
  value = object.value;
  $('#mySelect').append($('<option>', { value : key }).text(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'));