T.J*_*der 24
对于实际修改选项,你真的不需要jQuery.您可以通过分配框的length属性的options属性来清除旧选项SELECT,然后通过#add和添加新选项new Option().
以下是使用jQuery进行XHR部分然后直接执行选项的几个示例:
如果要从对象中的数组中绘制数据(在这种情况下,由options结果对象上的属性标识的数组):
JSON:
{
"options": [
{"value": "New1", "text": "New Option 1"},
{"value": "New2", "text": "New Option 2"},
{"value": "New3", "text": "New Option 3"}
]
}
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
$.ajax({
url: "http://jsbin.com/apici3",
dataType: "json",
success: function(data) {
var options, index, select, option;
// Get the raw DOM object for the select box
select = document.getElementById('theSelect');
// Clear the old options
select.options.length = 0;
// Load the new options
options = data.options; // Or whatever source information you're working with
for (index = 0; index < options.length; ++index) {
option = options[index];
select.options.add(new Option(option.text, option.value));
}
}
});
Run Code Online (Sandbox Code Playgroud)
如果您将对象的属性名称用作option值,并将属性值用作选项文本:
JSON:
{
"new1": "New Option 1",
"new2": "New Option 2",
"new3": "New Option 3"
}
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
$.ajax({
url: "http://jsbin.com/apici3/2",
dataType: "json",
success: function(data) {
var name, select, option;
// Get the raw DOM object for the select box
select = document.getElementById('theSelect');
// Clear the old options
select.options.length = 0;
// Load the new options
for (name in data) {
if (data.hasOwnProperty(name)) {
select.options.add(new Option(data[name], name));
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
更新:而不是
select.options.add(new Option(...));
Run Code Online (Sandbox Code Playgroud)
你也可以这样做:
select.options[select.options.length] = new Option(...);
Run Code Online (Sandbox Code Playgroud)
...我认为实际上我倾向于使用类似数组的add方法options(我不是把它称为数组,因为它有一个方法,add数组没有;因为如果你使用push,哪些数组确实有,它不起作用).
我已经测试了两种方法
......而且两者都有效.也许有Mac的人可以为我在OS X上试用Safari.
我会说两种方式得到非常非常好的支持.
| 归档时间: |
|
| 查看次数: |
32003 次 |
| 最近记录: |