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


当前回答

被警告。。。我在Android 2.2(Cyanogen 7.0.1)手机(T-Mobile G2)上使用jQuery Mobile 1.0b2和PhoneGap 1.0.0,根本无法使用.append()方法。我不得不像下面这样使用.html():

var options;
$.each(data, function(index, object) {
    options += '<option value="' + object.id + '">' + object.stop + '</option>';
});

$('#selectMenu').html(options);

其他回答

获取对象键以获取对象值。使用map()添加新选项。

常量选择值={“1”:“测试1”,“2”:“测试2”}const selectTest=document.getElementById('selectTest')Object.keys(selectValues).map(key=>selectTest.add(新选项(selectValues[key],key)))<select id=“selectTest”></select>

有一种使用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");

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

$.each比for循环慢每次,DOM选择都不是循环$(“#mySelect”).append()中的最佳实践;

因此,最佳解决方案如下

如果JSON数据resp为

[
    {"id":"0001", "name":"Mr. P"},
    {"id":"0003", "name":"Mr. Q"},
    {"id":"0054", "name":"Mr. R"},
    {"id":"0061", "name":"Mr. S"}
]

将其用作

var option = "";
for (i=0; i<resp.length; i++) {
    option += "<option value='" + resp[i].id + "'>" + resp[i].name + "</option>";
}
$('#mySelect').html(option);
$.each(selectValues, function(key, value) {
    $('#mySelect').append($("<option/>", {
        value: key, text: value
    }));
});
<!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>