二級級聯(lián)(原生js)

級聯(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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容