JS省、市、区三级联动

2022-08-15 14:08:35

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

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title></title><scriptsrc="./js/city.js"></script></head><body><formaction="#"method="get"><selectname="province"id="province"onfocus="add1()"onchange="add2()"><optionvalue="0">选择省份</option></select><selectname="city"id="city"onfocus="add2()"onchange="add3()"><optionvalue="0">选择城市</option></select> 市/区<selectname="county"id="county"><optionvalue="0">选择地方</option></select> 县/区</form></body><script>var pro= document.getElementById('province');var cit= document.getElementById('city');var county= document.getElementById('county');functionadd1(){
        pro.length= arr.length+1;for(var i=1;i<pro.length;i++){
			pro[i].innerHTML=arr[i-1].name;
            pro[i].value=i;}}functionadd2(){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;}}functionadd3(){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":["黄浦区","卢湾区","徐汇区","长宁区","静安区","普陀区","闸北区","虹口区","杨浦区","闵行区","宝山区?","嘉定区","浦东新区","金山区","松江区","青浦区","南汇区","奉贤区","崇明县","城桥镇"]}]}
  • 作者:Rachel_One
  • 原文链接:https://blog.csdn.net/Rachel_Qne/article/details/109154417
    更新时间:2022-08-15 14:08:35