城市联动效果

  • 作者:村长
  • 发布时间:2020-04-18 10:56
  • 分类:HTML+CSS
  • 标签: 热门推荐

城市联动效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>联动效果</title>
</head>
<body>
    
    <h1>请选择城市:</h1>
    <b>省份:</b>
    <select name="" id="province" onchange="getCity()"></select>
    <b>城市:</b>
    <select name="" id="city"></select>

    <script>
        var province = document.getElementById("province");
        var cityList = document.getElementById("city");

        var city = [];
        city["湖北省"] = ["武汉","襄阳","黄石","宜昌","咸宁"];
        city["湖南省"] = ["长沙","张家界","株洲"];
        city["广西省"] = ["南宁","桂林","柳州"];
        city["广东省"] = ["广州","深圳","清远","湛江"];
        //初始化展示数据
        //创建一个选项,用于存储这些省份,展示到对应的选项中
        //用循环遍历的方式取值出来存储展示
        for(var pro in city)
        {
            var option = document.createElement("option");
            option.value = pro;
            option.innerText = pro;
            //在省份选项框中展示
            province.appendChild(option);
        }
        getCity();
        //取省份对应的城市展示到另一个列表中
        function getCity()
        {
            //先把城市选项列表清空
            cityList.innerHTML = "";
            //再展示
            var province = document.getElementById("province").value;
            for(var i=0;i<city[province].length;i++)
            {
                var option = document.createElement("option");
                option.value = city[province][i];
                option.innerText = city[province][i];
                //在城市选项框中展示
                cityList.appendChild(option);
            }
        }

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


  • php程序员面试笔试宝典
琉忆编程库
加载中...
TOP