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


当前回答

这就是我对二维数组所做的:第一列是项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();}}

其他回答

var output = [];

$.each(selectValues, function(key, value)
{
  output.push('<option value="'+ key +'">'+ value +'</option>');
});

$('#mySelect').html(output.join(''));

这样,您只需“触摸DOM”一次。

我不确定最新的一行是否可以转换为$('#mySelect').html(output.join('')),因为我不知道jQuery的内部结构(可能它在html()方法中进行了一些解析)

对老@joshberry的回答进行了改进:

看起来plain.append也能像预期的那样工作,

$("#mySelect").append(
  $.map(selectValues, function(v,k){

    return $("<option>").val(k).text(v);
  })
);

或更短,

$("#mySelect").append(
  $.map(selectValues, (v,k) => $("<option>").val(k).text(v))
  // $.map(selectValues, (v,k) => new Option(v, k)) // using plain JS
);

JSON格式:

[{
    "org_name": "Asset Management"
}, {
    "org_name": "Debt Equity Foreign services"
}, {
    "org_name": "Credit Services"
}]

以及jQuery代码,用于填充Ajax成功时下拉列表的值:

success: function(json) {
    var options = [];
    $('#org_category').html('');  // Set the Dropdown as Blank before new Data
    options.push('<option>-- Select Category --</option>');
    $.each(JSON.parse(json), function(i, item) {
        options.push($('<option/>',
        {
           value: item.org_name, text: item.org_name
        }));
    });
    $('#org_category').append(options);  // Set the Values to Dropdown
}

如果您不必支持旧的IE版本,那么使用Option构造函数显然是一种可读且高效的解决方案:

$(new Option('myText', 'val')).appendTo('#mySelect');

它的功能等同于,但比:

$("<option></option>").attr("value", "val").text("myText")).appendTo('#mySelect');

这稍微更快更干净。

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>