更改选择列表的选项数组 [英] Change the options array of a select list
问题描述
有没有办法使用javascript或mootools来更改html选择列表的选项数组?
我需要用新的选项替换整个选项集。在我的ajax响应中,我收到一个填充了新HTML选项的数组,所以我尝试清空旧列表并添加新值,如下所示:
$( '元件')options.length = 0。
for(i = 0; i {
$('element')。options [i] = newSet [i];
$ / code>
上面的代码给了我循环内部一行未捕获的异常。 / b>
未捕获的异常:[Exception ...意外错误nsresult:0x8000ffff(NS_ERROR_UNEXPECTED)位置:JS框架
只需添加对我有用的内容即可:
/ *从json获取新选项* /
var new_options = response.options;
/ *从选择列表中删除所有选项* /
$('idresource')。empty();
/ *插入新选项从上面的数组中* /
for(var key in new_options)
{
var opt = document.createElement('option');
opt.text = new_options [key] ;
opt.value = key;
$('idresource').add(opt,null);
}
var new_options = ['Option 1','Option 2','Option 3' ];
/ *从选择列表中删除所有选项* /
$('yourSelectList')。empty();
/ *从上面的数组中插入新的* /
$ each(new_options,function(value){
new Element('option')
.set('text ',value)
.inject($('yourSelectList'));
});
Is there a way to change the options array of an html select list using javascript or mootools?
I need to replace the entire options set with a new one. In my ajax response I receive an array filled in with with the new HTML options, so I try to empty the old list and add new values as follows
$('element').options.length=0;
for (i=0; i<newSet.length; i++)
{
$('element').options[i]=newSet[i];
}
The above code gives me an uncaught exception on the line inside the loop.
uncaught exception: [Exception... "Unexpected error" nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame
Just to add what worked for me:
/* get new options from json*/
var new_options = response.options;
/* Remove all options from the select list */
$('idresource').empty();
/* Insert the new ones from the array above */
for (var key in new_options)
{
var opt = document.createElement('option');
opt.text = new_options[key];
opt.value = key;
$('idresource').add(opt, null);
}
var new_options = ['Option 1', 'Option 2', 'Option 3'];
/* Remove all options from the select list */
$('yourSelectList').empty();
/* Insert the new ones from the array above */
$each(new_options, function(value) {
new Element('option')
.set('text', value)
.inject($('yourSelectList'));
});
这篇关于更改选择列表的选项数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!