如何使用jQuery从JavaScript对象中添加选项到选择列表?

40 浏览
0 Comments

如何使用jQuery从JavaScript对象中添加选项到选择列表?

如何使用jQuery从JavaScript对象向添加选项的最佳方法?

我正在寻找一些我不需要插件来完成的东西,但我也会对现有的插件感兴趣。

这是我做的:

selectValues = { "1": "test 1", "2": "test 2" };
for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('' + selectValues[key] + '');
  }
}

一个干净/简单的解决方案:

这是matdumsa的一个简化和简化版本:

$.each(selectValues, function(key, value) {
     $('#mySelect')
          .append($('', { value : key })
          .text(value));
});

与matdumsa不同之处:(1)在append()内部删除选项的关闭标记,并将属性/属性移动到一个映射中作为append()的第二个参数。(2)

admin 更改状态以发布 2023年5月20日
0
0 Comments

var output = [];
$.each(selectValues, function(key, value)
{
  output.push('');
});
$('#mySelect').html(output.join(''));

以这种方式,您只需一次“触碰DOM”。

我不确定最新行是否可以转换为$('#mySelect').html(output.join('')), 因为我不知道jQuery内部(也许它在html()方法中进行了一些解析)

0
0 Comments

与其他答案一样,使用 jQuery 的方式:

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

0