級聯(lián)是多數(shù)情況下用于有上下級關(guān)系的場景。比如國家、城市;或者省、市;再或在 連鎖店、地址等等。

效果圖.png
css區(qū)寫法:
<style>
.hide{
display: none;
}
.show{
display: inline-block;
}
</style>
js區(qū)域的寫法:
<script type="text/javascript">
var country = ['中國', '美國','英國']
var city = [
['北京', '上海', '廣州','深圳'],
['紐約','華盛頓','洛杉磯'],
['倫敦']
];
//獲取dom
var countrySelect = document.getElementById("country");
var citySelect = document.getElementById("city");
//初始化國家下拉列表
for(var i = 0; i < country.length; i++) {
//新的option
var option = new Option()
//賦值
option.appendChild(document.createTextNode(country[i]))
//插入
countrySelect.appendChild(option)
}
//切換
countrySelect.addEventListener('change', function(){
//城市顯示
citySelect.className = 'show';
//另城市列表變?yōu)槌跏紶顟B(tài),可以注釋掉查看效果
citySelect.options.length = 1;
//如果國家選擇不為默認(rèn)值
if(countrySelect.selectedIndex != 0) {
//selectedIndex:屬性可設(shè)置或返回下拉列表中被選選項的索引號
countryIndex = countrySelect.selectedIndex - 1;
//遍歷相應(yīng)國家的城市
for (var j = 0; j < city[countryIndex].length; j++) {
//新的option
var cityOption = new Option()
//賦值
cityOption.appendChild(document.createTextNode(city[countryIndex][j]))
//插入
citySelect.appendChild(cityOption)
}
}
else{
//城市隱藏
citySelect.className = 'hide';
}
})
</script>
html區(qū)域?qū)懛ǎ?/p>
<body>
<select name="" id="country">
<option selected>請選擇國家</option>
</select>
<select name="" id="city" class="hide">
<option selected>請選擇城市</option>
</select>
</body>