在更改另一个</option> </select>的所选<option> </option>时更改<select>的<option>子节点

时间:2012-06-22 11:15:25

标签: javascript dom

所以我有这些javascript代码行,我需要删除所选select元素的所有子节点并向其添加新的选项元素。选项元素的值存储在“personaggi”数组中。 所以代码似乎适用于0,1和2的“k”值。当k = 3时,它不再正常工作,我找不到原因。功能应该是这样的:

response=xmlhttp.responseText;
var personaggi=response.substr(1).split("+");
select=document.getElementById('select_personaggi');
var length=select.childNodes.length;
for(k=0;k<length;k++){ 
    select.removeChild(select.childNodes[k]); 
}
for(i=0;i<personaggi.length;i++){ 
    var option=document.createElement('option'); 
    option.setAttribute('value', personaggi[i]); 
    var text=document.createTextNode(personaggi[i]); 
    option.appendChild(text); 
    option.appendChild(text); 
    select.appendChild(option); 
}

希望我能很好地解释我的问题:)

2 个答案:

答案 0 :(得分:1)

您基本上是在循环中从数组中删除元素...这将永远无法正常工作。数组的大小会随着时间的推移而变化,但是你会继续增加索引。

以相反的顺序迭代节点,或执行以下操作:

while(select.firstChild) {
    select.removeChild(select.firstChild);
}

答案 1 :(得分:1)

处理选择选项更简单,更清晰:

response=xmlhttp.responseText;
var personaggi=response.substr(1).split("+");
select=document.getElementById('select_personaggi');

var length = select.options.length;
for (k = 0; k < length; k++) {
    select.options[0] = null;
}

for (i = 0; i < personaggi.length; i++) {
    select.options.add(new Option(personaggi[i], personaggi[i], true, false));
}
相关问题