HTML二级联动--城市省份

HTML二级联动--城市省份

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
        div {
            width: 500px;
            margin: 30px auto;
        }

        select {
            width: 100px;
        }
    </style>


</head>

<body>

    <div>
        <select name="" id="province">
            <option value="0">选择省</option>
            <option value="1">湖北</option>
            <option value="2">湖南</option>
        </select>
        <select name="" id="city">
            <option value="0">选择市</option>
        </select>
    </div>

    <script>
        let province = document.getElementById('province');
        let city = document.getElementById('city');
        //通过document.getElementById()函数是通过id值获取节点元素

        province.onchange = function () {
            createCity();
        }   //将createCity()函数绑定到province.onchange事件上

        //创建city信息
        function createCity() {
            //获取选中项值  或直接用:province.value
            let val = province.options[province.selectedIndex].value;
            //使用option[]数组创建更多的选项
            //selectedIndex 属性可设置或返回下拉列表中被选选项的索引号
            
            let ops;

            switch (val) {
                case '0':  //case用字符串
                    city.innerHTML = '<option value="0">选择市</option>';
                    // innerHTML 属性设置或返回表格行的开始和结束标签之间的HTML。这里就是在select标签之间添加option选择                        项。
                    break;
                case '1':
                    city.innerHTML = '';  //清空已存在的选择项,以便更新选择项
                    ops = createOps(0, '武汉');
                    city.append(ops);     //append()函数添加新的选择项
                    ops = createOps(1, '黄石');
                    city.append(ops);
                    break;
                case '2':
                    city.innerHTML = '';
                    ops = createOps(0, '长沙');
                    city.append(ops); 
                    ops = createOps(1, '湘潭');
                    city.append(ops);
                    break;
            }

        }

        function createOps(val, cname) {
            let ops = document.createElement('option'); //createElement 创建一个空option
            ops.value = val;
            ops.innerHTML = cname;
            return ops;
        }
        
    </script>
</body>

</html>

posted @ 2021-09-30 21:44  rlch  阅读(801)  评论(0)    收藏  举报