級(jí)聯(lián)是多數(shù)情況下用于有上下級(jí)關(guān)系的場(chǎng)景。比如國(guó)家洋访、城市砰诵;或者省、市捌显;再或在 連鎖店、地址等等总寒。
css區(qū)寫法:
<style>
.hide{
display: none;
}
.show{
display: inline-block;
}
</style>
js區(qū)域的寫法:
<script type="text/javascript">
var country = ['中國(guó)', '美國(guó)','英國(guó)']
var city = [
['北京', '上海', '廣州','深圳'],
['紐約','華盛頓','洛杉磯'],
['倫敦']
];
//獲取dom
var countrySelect = document.getElementById("country");
var citySelect = document.getElementById("city");
//初始化國(guó)家下拉列表
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;
//如果國(guó)家選擇不為默認(rèn)值
if(countrySelect.selectedIndex != 0) {
//selectedIndex:屬性可設(shè)置或返回下拉列表中被選選項(xiàng)的索引號(hào)
countryIndex = countrySelect.selectedIndex - 1;
//遍歷相應(yīng)國(guó)家的城市
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>請(qǐng)選擇國(guó)家</option>
</select>
<select name="" id="city" class="hide">
<option selected>請(qǐng)選擇城市</option>
</select>
</body>