对于实际修改选项,您实际上并不需要jQuery。您可以通过分配框
length属性的
options属性来清除旧选项
SELECT,然后通过
#add和添加新选项
newOption()。
这是使用jQuery作为XHR部分,然后直接执行选项的几个示例:
从数组中:
如果要从对象内的数组(在本例中为由
options结果对象上的属性标识的数组)绘制数据:
JSON:
{ "options": [ {"value": "New1", "text": "New Option 1"}, {"value": "New2", "text": "New Option 2"}, {"value": "New3", "text": "New Option 3"} ]}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)); } }});现场例子
直接来自对象:
如果将对象的属性名称用作
option值,并将属性值用作选项文本:
JSON:
{ "new1": "New Option 1", "new2": "New Option 2", "new3": "New Option 3"}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)); } } }});现场例子
更新 :而不是
select.options.add(new Option(...));
您也可以:
select.options[select.options.length] = new Option(...);
现场例子
…我认为实际上我倾向于
add在
options类似数组的东西上使用该方法(我之所以不称其为数组,是因为它有一个方法
add,该数组没有该方法;并且因为如果使用
push,哪些数组
确实 有,但不起作用)。
我已经测试了两种方法
- IE6,7,8(Windows)
- Chrome(Linux和Windows)
- Firefox(Linux和Windows)
- Opera(Linux和Windows)
- Safari(Windows)
…两者都起作用。也许有Mac的人可以为我在OS X上尝试Safari。
我想说两种方式都非常非常受支持。



