使用 jQuery 向 JavaScript 对象中的选择添加选项的最佳方法是什么? [英] What is the best way to add options to a select from a JavaScript object with jQuery?
问题描述
使用 jQuery 从 JavaScript 对象向 添加选项的最佳方法是什么?
What is the best method for adding options to a <select>
from a JavaScript object using jQuery?
我正在寻找不需要插件的东西,但我也对现有的插件感兴趣.
I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.
这就是我所做的:
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 的版本:
This is a cleaned up and simplified version of matdumsa's:
$.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().
推荐答案
与其他答案相同,采用 jQuery 方式:
The same as other answers, in a jQuery fashion:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value", key)
.text(value));
});
这篇关于使用 jQuery 向 JavaScript 对象中的选择添加选项的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!