使用jquery动态添加下拉列表值(选项)

15 浏览
0 Comments

使用jquery动态添加下拉列表值(选项)

如何使用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()中省略了选项的关闭标记,(2)将属性/属性移到map中,作为append()的第二个参数。

admin 更改状态以发布 2023年5月23日
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