我正在创建一个javascript方法,它根据之前选择的单选按钮来填充列表。因为它依赖于动物或植物来填充它,所以当我必须在它已经被填充之后才能填充它时,我的问题就来了。我的意思是,植物下拉列表有88个元素,动物是888个,当我尝试从动物回到植物时,我得到了一些动物。我知道我的控制器方法工作正常,因为它返回我选择的值,所以问题出在javascript方法上。代码如下:
if(selector == "sOrder")
alert(document.getElementById(selector).options.length);
for (i = 0; i < document.getElementById(selector).options.length; i++) {
document.getElementById(selector).remove(i);
}
if (selector == "sOrder")
alert(document.getElementById(selector).options.length);
document.getElementById(selector).options[0] = new Option("-select-", "0", true, true);
for (i = 1; i <= data.length; i++) {
document.getElementById(selector).options[i] = new Option(data[i - 1].taxName, data[i - 1].taxRecID);}奇怪的是,当我进入这个方法时,我试图擦除dropdownlist中的所有元素,以便随后填充它。因为sOrder是我之前选择的选择器,所以我得到了元素,问题是第一个警报我得到了正确的结果888,但在第二个警报中,我应该得到一个0,对吗?它显示444,所以当我再次填充它时,它只是覆盖了前88个植物,然后是动物,直到444。我做错了什么?
先谢谢你们,维克多
发布于 2010-03-25 18:11:44
从本质上讲,您是通过使用索引从头到尾删除列表的,但是当您这样做时,每个连续项的索引都会减少。如果从头到尾删除,则索引保持不变,您可以按索引删除它们。
替换
for (i = 0; i < document.getElementById(selector).options.length; i++) {
document.getElementById(selector).remove(i);
}使用
for (i = document.getElementById(selector).options.length -1; i > 0 ; i--) {
document.getElementById(selector).remove(i);
}从选择框中删除所有项的更简单的方法可能是使用:
document.getElementById(selector).innerHTML="";这将拉出select中的html。(请注意,我只在Firefox 3.6.2中测试过这一点,但我相信这应该可以在大多数现代浏览器中工作)
发布于 2010-03-25 18:15:43
我认为在remove循环中有一个错误
选择器if(选择器“document.getElementById(selector).options.length;”) alert(document.getElementById(selector).options.length);
(i = 0;i
实际上,当您删除元素时,document.getElementById(selector).options.length会发生变化。
因此,在第一次迭代中,您使用length=888,然后删除一个元素
在第二次迭代中,您有length=887 (和i=1)等。
在第444次迭代中,您有i=443和length=444,并且在删除第444个元素后循环退出。
https://stackoverflow.com/questions/2514549
复制相似问题