使用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();}}

其他回答

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

与其在任何地方重复相同的代码,我建议您最好编写自己的jQuery函数,如:

jQuery.fn.addOption = function (key, value) {
    $(this).append($('<option>', { value: key }).text(value));
};

然后,要添加选项,只需执行以下操作:

$('select').addOption('0', 'None');

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

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

它的功能等同于,但比:

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

被警告。。。我在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);

将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