js的三级联动在初学者眼中是比较难的,因为嵌套的东西太多,容易迷。
先放代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
* {
font-size: 20px;
}
</style>
</head>
<body>
省:<select name="province" id="province" onchange="showCity()">
</select>
市:<select name="city" id="city" onchange="showCounty()">
</select>
县:<select name="county" id="county">
</select>
<script src="./js/citys.js"></script>
<script>
let _province = document.querySelector("#province");
let _city = document.querySelector("#city");
let _county = document.querySelector("#county");
//获取省的信息
let provinces = citys.districts[0].districts;//获得省的对象
for (let province of provinces) {
_province.innerHTML += `<option value="${province.adcode}">${province.name}</option>`
}
//获得省下面的市的信息
showCity();
function showCity() {
_city.innerHTML = "";//清除上次选择留下的信息
let provinceCode = _province.value;//获得复选框选定时的value值
let checkProvince = provinces.find(function(item) {
return item.adcode == provinceCode;
})//筛选与复选框选定时的value值相同的省信息
for (let city of checkProvince.districts) {
_city.innerHTML += `<option value="${city.adcode}">${city.name}</option>`
}//输出市的信息
showCounty();//变换市的信息时也要变换县的信息
}
//获得市下面的县的信息
showCounty();
function showCounty() {
_county.innerHTML = "";
let provinceCode = _province.value;
let checkProvince = provinces.find(function(item) {
return item.adcode == provinceCode;
})
let cityCode = _city.value;
let checkCity = checkProvince.districts.find(function(item) {
return item.adcode == cityCode;
}) //筛选省对应的市
for (let county of checkCity.districts) {
_county.innerHTML += `<option value="${county.adcode}">${county.name}</option>`
}
}
</script>
</body>
</html>
引用的js(<script src="./js/citys.js"></script>)太多放不下,我放在另外一篇文章里面。
结果展示:
一级菜单
二级菜单:
三级菜单