使用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方式:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value", key)
                    .text(value)); 
});

其他回答

我决定插嘴。

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

所有这些答案似乎都不必要地复杂。您只需要:

var options = $('#mySelect').get(0).options;
$.each(selectValues, function(key, value) {
        options[options.length] = new Option(value, key);
});

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

这就是我对二维数组所做的:第一列是项I,添加到<option>的innerHTML。第二列是record_id i,添加到<option>的值:

PHP文件$items=$dal->get_new_items();//从数据库获取数据$items_arr=数组();$i=0;foreach($items作为$item){$first_name=$item->first_name;$last_name=$item->last_name;$date=$item->date;$show=$first_name。" " . $姓氏。", " . $日期$request_id=$request->request_id;$items_arr[0][$i]=$show;$items_arr[1][$i]=$request_id;$i++;}echo json_encode($items_arr);JavaScript/Ajax函数ddl_items(){if(window.XMLHttpRequest){//Internet Explorer 7+、Firefox、Chrome、Opera和Safari的代码xmlhttp=new XMLHttpRequest();}其他{//Internet Explorer 6和Internet Explorer 5的代码xmlhttp=新ActiveXObject(“Microsoft.xmlhttp”);}xmlhttp.onreadystatechange=函数(){如果(xmlhttp.readyState==4&&xmlhttp.status==200){var arr=JSON.parse(xmlhttp.responseText);var lstbx=document.getElementById('my_listbox');对于(变量i=0;i<arr.length;i++){var option=新选项(arr[0][i],arr[1][i]);lstbx.options.add(选项);}}};xmlhttp.open(“GET”,“Code/GET_items.php?dummy_time=”+new Date().getTime()+“”,true);xmlhttp.send();}}

与其他答案相同,以jQuery方式:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value", key)
                    .text(value)); 
});

我把两个最好的答案组合成一个好答案。

var outputConcatenation = [];

$.each(selectValues, function(i, item) {   
     outputConcatenation.push($("<option></option>").attr("value", item.key).attr("data-customdata", item.customdata).text(item.text).prop("outerHTML"));
});

$("#myselect").html(outputConcatenation.join(''));