什么是使用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()中删除了选项的关闭标签,(2) 将属性/属性移动到一个映射中作为append()的第二个参数。
Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().
value
是一个字符串(并且是硬编码的),所以它不需要加引号。 - Darryl Hein