js 实现级联下拉菜单

 

 

 

<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<!--当用户选定或取消选定时,触发onchange-->
省:<select onchange="change()" id="pro">
    <option>河北省</option>
    <option>山西省</option>
</select>
市:<select id="city">

</select>

<script>
    function change() {
        //根据省的变化生成对应的市
        //1.找到当前被选中的省
        var pro = document.getElementById('pro');

        //selectedIndex 属性可设置或返回下拉列表中被选选项的索引号
        var cunrrentPro = pro.options[pro.selectedIndex];

        //js中清空数组可以给数组length=0
        //让长度等于0因为了让一个省只有自己的市,不会出现别的省的市
        document.getElementById('shi').options.length = 0;

        //2.根据选中的省来找到对应的市
        switch (cunrrentPro.text) {
            case '河北省':
                var city = document.getElementById('city');
                //select对象数组:options[],返回包含下拉列表中的所有选项的一个数组
                city.options[city.options.length] = new Option('石家庄', 'sjz');//此Option传的是text和value的值
                city.options[city.options.length] = new Option('邢台', 'xt');
                break;
            case '山西省':
                var city = document.getElementById('city');
                city.options[city.options.length] = new Option('太原', 'ty');
                city.options[city.options.length] = new Option('大同', 'dt');
                break;
        }

    }
</script>
</body>
</html>

 

posted @ 2019-09-05 19:56  此间的我  阅读(1406)  评论(0编辑  收藏  举报