鉴于此html:
<select id="fruits" name="fruits">
<option selected>Please select a fruit</option>
<option>Apple</option>
<option>Mango</option>
<option>Banana</option>
</select>
<select id="options" name="options">
<option selected>--Select a fruit first--</option>
<option>is sometimes green</option>
<option>is sometimes yellow</option>
<option>is sometimes blood red</option>
<option>is sometimes sour</option>
<option>is sometimes sweet</option>
<option>is sometimes bitter</option>
</select>
如果我从第一个下拉菜单中选择苹果,只选择
选项应该可用。其他人应该被删除/隐藏。 我正在寻找一个JAVASCRIPT ONLY解决方案;我不认识jQuery!
请帮忙!
答案 0 :(得分:1)
此html将函数setOption
附加到onchange
- 事件。根据quirksmode the change event is buggy 。因此,您可能必须修复/扩展以提高跨浏览器兼容性。
<select id="s1" onchange="setOptions()">
<option>Pizza</option>
<option>Pasta</option>
<option>HotDogs</option>
</select>
<select id="s2">
<option>Pizza 1</option>
<option>Pizza 2</option>
<option>Pizza 3</option>
</select>
在第一个选择s2
的所选选项发生更改后,此javascript会更改第二个选择s1
的选项 - onchange-event被触发:
function setOptions()
{
document.getElementById('s2').options.length = 0; // remove all options
var selIndex = document.getElementById("s1").selectedIndex;
if(selIndex == 0)
addAllOptions('s2', ["Pizza Diavolo","Pizza Veggie"]);
else if(selIndex == 1){
addAllOptions('s2', ["Pasta Napoli","Pasta Primavera"]);
}
else{
addAllOptions('s2', ["Hot Dog Chilie King","Hot Dog Silent Wiener"]);
}
}
并添加选项
function addAllOptions(selectID, values)
{
var arrayLength = values.length;
for (var i = 0; i < arrayLength; i++) {
appendOptionLast(selectID,values[i]);
}
}
此功能可能还需要增强,以提高跨浏览器的兼容性。
// see http://www.mredkj.com/tutorials/tutorial005.html
function appendOptionLast(selectID, num)
{
var elSel = document.getElementById(selectID);
var elOptNew = document.createElement('option');
elOptNew.text = num;
elOptNew.value = 'a_' + num;
try {
elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew); // IE only
}
}