【发布时间】:2016-09-02 05:36:02
【问题描述】:
我有 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);
}
}
}
});
});
【问题讨论】:
-
您遇到问题是因为在您的
for循环中,当您遇到一个元素时将其删除,这会从options的节点列表中删除该节点
标签: javascript forms dom select