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


当前回答

您可以使用以下代码迭代json数组

$('<option/>').attr(“value”,“someValue”).text(“Option1”).appendTo(“#my select id”);

其他回答

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

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

这里可以找到jQuery插件:使用jQuery和AJAX自动填充选择框。

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

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

将HTML选择id设置为以下行。在这里,mySelect用作select元素的id。

   var options = $("#mySelect");

然后获取这个场景中的selectValues对象,并将其设置为每个循环的jquery。它将相应地使用对象的值和文本,并将其附加到选项选择中,如下所示。

$.each(selectValues, function(val, text) {
            options.append(
             $('<option></option>').val(val).html(text)
          );
      });

当选择下拉列表时,这将显示文本作为选项列表,一旦选择文本,将使用所选文本的值。

Eg.

“1”:“测试1”,“2”:“测试2”,

下拉列表,

显示名称:测试1->值为1显示名称:测试2->值为2

<!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>