使用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)的第二个参数移动到映射中。
JSON格式:
[{
"org_name": "Asset Management"
}, {
"org_name": "Debt Equity Foreign services"
}, {
"org_name": "Credit Services"
}]
以及jQuery代码,用于填充Ajax成功时下拉列表的值:
success: function(json) {
var options = [];
$('#org_category').html(''); // Set the Dropdown as Blank before new Data
options.push('<option>-- Select Category --</option>');
$.each(JSON.parse(json), function(i, item) {
options.push($('<option/>',
{
value: item.org_name, text: item.org_name
}));
});
$('#org_category').append(options); // Set the Values to Dropdown
}
有一种使用MicrosoftTemplateing方法的方法,目前正在提议将其纳入jQuery核心。使用模板功能更强大,因此对于最简单的场景,它可能不是最佳选项。有关更多详细信息,请参阅Scott Gu概述这些功能的帖子。
首先包括github提供的模板js文件。
<script src="Scripts/jquery.tmpl.js" type="text/javascript" />
下一步设置模板
<script id="templateOptionItem" type="text/html">
<option value=\'{{= Value}}\'>{{= Text}}</option>
</script>
然后使用数据调用.render()方法
var someData = [
{ Text: "one", Value: "1" },
{ Text: "two", Value: "2" },
{ Text: "three", Value: "3"}];
$("#templateOptionItem").render(someData).appendTo("#mySelect");
我在博客中详细介绍了这种方法。