<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>11</title>
</head>
<body>
省:<select id="province"></select>
市:<select id="city"></select>
县:<select id="county"></select>
<script src="js/citys.js"></script> **//外联js的地址**
<script>
## //找到省级
var provinces=citys.districts[0].districts;
console.log(provinces);
var _province=document.querySelector("#province");
var _city=document.querySelector("#city");
var _county=document.querySelector("#county");
provinces.forEach(function(obj){
_province.innerHTML+=`<option value="${obj.adcode}">${obj.name}</option>`
})
showCitys(); *//第一次需要初始加载*
_province.onchange=function(){
showCitys(); **//加载市级**
showCounty(); **//加载县级**
}
## //找到市级
function showCitys(){
_city.innerHTML="";
var code=_province.value; **//找市级需要先找到省级**
var province=provinces.find(function(obj){
return obj.adcode==code;
})
var citys=province.districts; **//遍历市级数组 找到市级**
citys.forEach(function(obj){
_city.innerHTML+=`<option value="${obj.adcode}">${obj.name}</option>`
})
}
showCounty(); **//第一次需要初始加载,此后是切换加载**
_city.onchange=function(){
showCounty();
}
function showCounty(){
_county.innerHTML="";
var cityCode=_city.value;
var provinceCode=_province.value; **//省编码
//根据省编码获取对应的省对象**
var province=provinces.find(function(obj){
return obj.adcode==provinceCode;
})
var citys=province.districts; **//根据省级数组找对应市级对象**
var city=citys.find(function(ojb){
return ojb.adcode==cityCode;
})
var countys=city.districts; **//根据市级数组找对应县级对象**
countys.forEach(function(obj){
_county.innerHTML+=`<option value="${obj.adcode}">${obj.name}</option>`
})
}
</script>
</body>
</html>
## // 自己建一个js文件 名: citys.js 把下列内容放进去
[js地址(http://127.0.0.1:8848/workspace/2022-8.04/js/citys.js)
/* var citys = {
"districts": [{
"adcode": "100000",
"name": "中华人民共和国",
"districts": [{
"adcode": "410000",
"name": "河南省",
"districts": [{
"citycode": "0379",
"adcode": "410300",
"name": "洛阳市",
"center": "112.434468,34.663041",
"level": "city",
"districts": [{
"citycode": "0379",
"adcode": "410323",
"name": "新安县",
"center": "112.141403,34.728679",
"level": "district",
"districts": []
}]
},
{
"citycode": "0398",
"adcode": "411200",
"name": "三门峡市",
"center": "111.194099,34.777338",
"level": "city",
"districts": [{
"citycode": "0398",
"adcode": "411221",
"name": "渑池县",
"center": "111.762992,34.763487",
"level": "district",
"districts": []
}]
}
]
},
{
"citycode": [],
"adcode": "440000",
"name": "广东省",
"center": "113.280637,23.125178",
"level": "province",
"districts": [{
"citycode": "0754",
"adcode": "440500",
"name": "汕头市",
"center": "116.708463,23.37102",
"level": "city",
"districts": [{
"citycode": "0754",
"adcode": "440513",
"name": "潮阳区",
"center": "116.602602,23.262336",
"level": "district",
"districts": []
}]
}]
}]
}]
} */
初始![初始页面 当改变省级市 市县级会随之改变](https://img-blog.csdnimg.cn/f4813d59beb44f63b0ff6878fc547fe9.png#pic_center)。
![ 当改变省级市 市县级会随之改变](https://img-blog.csdnimg.cn/f5e26c6ac21f419c8afa7c46075108ea.png#pic_center)