【JS】省、市、区三级联动

上周末作业
拷贝的大佬的代码
大概要写成这个样子,没有做css
三级联动
选择不同省份时,自动显示不同市区
三级联动
HTML代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="./js/city.js"></script>
</head>
<body>
    <form action="#" method="get">
        <select name="province" id="province" onfocus="add1()" onchange="add2()">
            <option value="0">选择省份</option>
        </select><select name="city" id="city" onfocus="add2()" onchange="add3()">
            <option value="0">选择城市</option> 
        </select> 市/区
        <select name="county" id="county">
            <option value="0">选择地方</option> 
        </select> 县/区
    </form>
</body>
<script>
    var pro = document.getElementById('province');
    var cit = document.getElementById('city');
    var county = document.getElementById('county');
    function add1(){
        pro.length = arr.length+1;
		for(var i=1;i<pro.length;i++){
			pro[i].innerHTML=arr[i-1].name;
            pro[i].value=i;
        }
    }
    function add2(){
        if(pro.length == 1){
            return;
        }
        cit.value=0;
        var cityList=arr[pro.value-1].city;
        cit.length=cityList.length+1;
        for(var i=1;i<cit.length;i++){
            cit[i].innerText=cityList[i-1].name;
            cit[i].value=i;
        }
    }
    function add3(){
        var countyList = arr[pro.value-1].city[city.value-1].districtAndCounty;
        console.log(countyList)
        county.length = countyList.length+1;
        for(var i=1;i<county.length;i++){
            county[i].innerText=countyList[i-1];
            county[i].value=i;
        }
    }
</script>
</html>

这里连接了外部js文件,文件比较大,放一部分在上面,可以复制到内联js文件里。

var arr=[
    {
        "name": "北京市",
        "city": [
            {
                "name": "北京市",
                "districtAndCounty": ["东城区", "西城区", "崇文区", "宣武区", "朝阳区", "丰台区", "石景山区", "海淀区", "门头沟区", "房山区", "通州区", "顺义区", "昌平区", "大兴区", "怀柔区", "平谷区", "密云县", "延庆县", "延庆镇"]
            }
        ]
    },
    {
        "name": "天津市",
        "city": [
            {
                "name": "天津市",
                "districtAndCounty": ["和平区", "河东区", "河西区", "南开区", "河北区", "红桥区", "塘沽区", "汉沽区", "大港区", "东丽区", "西青区", "津南区", "北辰区", "武清区", "宝坻区", "蓟县", "宁河县", "芦台镇", "静海县", "静海镇"]
            }
        ]
    },
    {
        "name": "上海市",
        "city": [
            {
                "name": "上海市",
                "districtAndCounty": ["黄浦区", "卢湾区", "徐汇区", "长宁区", "静安区", "普陀区", "闸北区", "虹口区", "杨浦区", "闵行区", "宝山区?", "嘉定区", "浦东新区", "金山区", "松江区", "青浦区", "南汇区", "奉贤区", "崇明县", "城桥镇"]
            }
        ]
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值