直接上代码
<!DOCTYPE html>
<html>
<head>
<title>省市区联动</title>
<style>
* {
padding: 0px;
margin: 0px;
}
.select {
text-align: center;
margin-top: 200px;
}
select {
background-color: #eee;
}
</style>
<script src="jquery-3.4.1.min.js"></script>
<script>
var AddressStr = {
Provinces: [
{
province:"省1",
cities: [
{
city: "市11",
countries: [
{country: "区11"},
{country: "区12"},
{country: "区13"}
]
},
{
city: "市12",
countries: [
{country: "区11"},
{country: "区12"},
{country: "区13"}
]
},
{
city: "市13",
countries: [
{country: "区11"},
{country: "区12"},
{country: "区13"}
]
}
]
},
{
province: "省2",
cities: [
{
city: "市21",
countries: [
{country: "区21"},
{country: "区22"},
{country: "区23"}
]
},
{
city: "市22",
countries: [
{country: "区21"},
{country: "区22"},
{country: "区23"}
]
},
{
city: "市23",
countries: [
{country: "区21"},
{country: "区22"},
{country: "区23"}
]
}
]
}
]
};
//加载时就将省份的选择项全部显示出来,根据JSON数据来添加option
onload = function () {
//找到省对象,为其动态创建option
var province = document.getElementById("Province");
// console.log(typeof province);
for(var i = 0;i < AddressStr.Provinces.length;i++){
//根据所给数据创建option
let option = document.createElement("option");
option.innerHTML = AddressStr.Provinces[i].province;
province.appendChild(option);
}
}
//记录当前选择的省份的index
var ProvinceIndex;
function ShowProvince(options) {
var selectedIndex = options.selectedIndex;
ProvinceIndex = selectedIndex-1;
//第一个不用处理,因为是提示信息
if(selectedIndex>0){
let cities = AddressStr.Provinces[selectedIndex-1].cities;
//找到市对象,动态添加option
let CityOpts= document.getElementById("City");
//防止更换省份时候市对应加上之前选择的省份的市
CityOpts.innerHTML = "<option>=请选择市=</option>>";
for(var i= 0;i < AddressStr.Provinces[selectedIndex-1].cities.length;i++){
let option = document.createElement("option");
option.innerHTML = AddressStr.Provinces[selectedIndex-1].cities[i].city;
CityOpts.appendChild(option);
}
}
}
function ShowCity(options) {
var selectedIndex = options.selectedIndex;
if(selectedIndex>0){
let countries = AddressStr.Provinces[ProvinceIndex].cities[selectedIndex-1].countries;
let CountryOpts = document.getElementById("Country");
//防止更换市的时候县对应加上之前选择的市的下的县
CountryOpts.innerHTML = "<option>=请选择县=</option>>";
for(let index in countries){
let option = document.createElement("option");
option.innerHTML = countries[index].country;
CountryOpts.appendChild(option);
}
}
}
</script>
</head>
<body>
<div class="select">
<select id="Province" onchange="ShowProvince(this);">
<option value="">=请选择省=</option>
</select>
<select id="City" onchange="ShowCity(this);">
<option>=请选择市=</option>
</select>
<select id="Country">
<option>=请选择县=</option>
</select>
</div>
</body>
</html>
=请选择省= =请选择市= =请选择县=
拿着随便用,能看懂就看懂,看不懂就换个看,别看这个,这个就是垃圾