下面是一些可以用来完成此任务的通用js。
这段代码是有意泛型的,因此您需要使其适用于您的场景。您可以加载各种状态,并使用“js display toggle”类隐藏它们。当从“基本”选择菜单中选择适当的国家/地区时,您将删除切换类并显示这些国家/地区。
(function(d, undefined) {
\'use strict\';
var display = \'js-display-toggle\',
elems = d.getElementsByClassName(\'items\');
function addToAll() {
Array.prototype.slice.call(elems, 0).forEach(function(el, i) {
el.classList.add(\'js-display-toggle\');
console.log(\'add\');
});
}
function delegator(event) {
switch (event.type) {
case \'change\':
if (event.target.id === \'base\') {
addToAll();
switch (event.target.options.selectedIndex) {
case 1:
console.log(\'1\');
d.getElementById(\'seleks\').classList.remove(display);
break;
case 2:
console.log(\'2\');
d.getElementById(\'selectionField\').classList.remove(display);
break;
case 3:
console.log(\'3\');
d.getElementById(\'cars\').classList.remove(display);
break;
default:
}
}
break;
}
}
d.addEventListener(\'change\', delegator, false);
}(document, undefined));
.js-display-toggle {
display: none !important;
visibility: hidden !important;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>How do you filter the list of states when country is selected?</title>
</head>
<body>
<form id="my-form">
<select id="base">
<option value="0">select one</option>
<option value="1">first</option>
<option value="2">second</option>
<option value="3">third</option>
</select>
<select id="seleks" class="js-display-toggle items">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select>
<select id="selectionField" class="js-display-toggle items">
<option value="CA">California -- CA</option>
<option value="CO">Colorado -- CO</option>
<option value="CN">Connecticut -- CN</option>
</select>
<select id="cars" class="js-display-toggle items">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</form>
</body>
</html>