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


当前回答

有一种使用MicrosoftTemplateing方法的方法,目前正在提议将其纳入jQuery核心。使用模板功能更强大,因此对于最简单的场景,它可能不是最佳选项。有关更多详细信息,请参阅Scott Gu概述这些功能的帖子。

首先包括github提供的模板js文件。

<script src="Scripts/jquery.tmpl.js" type="text/javascript" />

下一步设置模板

<script id="templateOptionItem" type="text/html">
    <option value=\'{{= Value}}\'>{{= Text}}</option>
</script>

然后使用数据调用.render()方法

var someData = [
    { Text: "one", Value: "1" },
    { Text: "two", Value: "2" },
    { Text: "three", Value: "3"}];

$("#templateOptionItem").render(someData).appendTo("#mySelect");

我在博客中详细介绍了这种方法。

其他回答

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

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

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

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

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

附加它,

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

甚至更好

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

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

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

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

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