我有 3 列 HTML 选择字段,需要根据之前的选择字段加载选项。
第 2 列值中的选择将取决于第 1 列选择中的选定值。我在下面有这个原始 JavaScript,它向 HTML 选择字段添加 2 个选择选项,然后根据选择 1 中的选择值删除 2 个。
我的问题是,删除 2 个选择字段选项的部分并没有删除两个选项,而是删除了其中的 1 个。
演示:http://jsfiddle.net/jasondavis/croh2nj8/3/
我意识到其中一些使用了 jQuery,但目标是在有问题的这部分使用不带 jQuery 的原始 JS....
$(document).ready(function() {
$("#action").change(function() {
var el = $(this) ;
var selectAttributeEl = document.getElementById('action-attribute');
if(el.val() === "form" ) {
var option = document.createElement('option');
option.text = 'Name';
var option2 = document.createElement('option');
option2.text = 'ActionURL';
selectAttributeEl.add(option);
selectAttributeEl.add(option2);
}else if(el.val() === "link" ) {
for (var i=0; i<selectAttributeEl.length; i++){
if (selectAttributeEl.options[i].value == 'Name'){
selectAttributeEl.remove(i);
}else if(selectAttributeEl.options[i].value == 'ActionURL'){
selectAttributeEl.remove(i);
}
}
}
});
});
最佳答案
问题出在您遍历 selectobject.options
的 for
循环中。当第一个 if
条件为真时,您可以通过删除 Name
选项来改变 selectobject.options
。在循环的下一次迭代中,selectobject.options[i]
现在返回 undefined
。
让我们通过 for
循环来演示:
i
为0,对应选项ID
,没有任何反应。i
为1,对应选项Class
,没有任何反应。i
为2,对应选项Name
,if
语句有效,去掉Name
选项。现在selectobject.options
的length
为 3。i
为3,对应undefined
。也就是说,selectobject.options[3]
是undefined
,因为循环的前一次迭代从selectobject.options
中删除了一个项目。
一种可能的解决方案,在 if
和 else
语句中,您可以将 i
重置为原来的状态,使用 i--
。这是一个 updated jsFiddle .另一种选择是通过 selectobject.options
向后循环,因为改变后面的项目不会影响计数器,因为它移动到前面的项目。
还有其他方法可以纠正这个问题,比如根据您希望保留在选项中的值创建一个新的 options
数组,然后将新选项加载到 select
。
关于javascript - 使用 JavaScript 删除超过 1 个选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084344/