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


当前回答

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

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

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

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

其他回答

获取对象键以获取对象值。使用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方式:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value", key)
                    .text(value)); 
});
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()方法中进行了一些解析)

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

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

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