js省市区三级联动代码
时间: 2024-06-18 10:02:43 浏览: 177
省市区三级联动js代码
4星 · 用户满意度95%
JS省市区三级联动是一个非常常用的前端交互功能,实现方式有很多,以下是一个简单的实现方式:
HTML代码:
```html
<select id="province">
<option value="">请选择省份</option>
</select>
<select id="city">
<option value="">请选择城市</option>
</select>
<select id="district">
<option value="">请选择地区</option>
</select>
```
JS代码:
```javascript
var areaData = [
{
name: "北京市",
city: [
{
name: "市辖区",
district: [
"东城区",
"西城区",
"朝阳区",
"丰台区",
"石景山区",
"海淀区",
"门头沟区",
"房山区",
"通州区",
"顺义区",
"昌平区",
"大兴区",
"怀柔区",
"平谷区",
"密云区",
"延庆区"
]
}
]
},
{
name: "天津市",
city: [
{
name: "市辖区",
district: [
"和平区",
"河东区",
"河西区",
"南开区",
"河北区",
"红桥区",
"东丽区",
"西青区",
"津南区",
"北辰区",
"武清区",
"宝坻区",
"滨海新区",
"宁河区",
"静海区",
"蓟州区"
]
}
]
},
//省市数据省略...
];
var province = document.getElementById("province");
var city = document.getElementById("city");
var district = document.getElementById("district");
//初始化省份数据
for(var i=0;i<areaData.length;i++){
var option = document.createElement("option");
option.innerText = areaData[i].name;
province.appendChild(option);
}
//选择省份后,初始化城市数据
province.onchange = function(){
var index = this.selectedIndex;
city.innerHTML = "<option value=''>请选择城市</option>";
district.innerHTML = "<option value=''>请选择地区</option>";
if(index!=0){
var cityData = areaData[index-1].city;
for(var i=0;i<cityData.length;i++){
var option = document.createElement("option");
option.innerText = cityData[i].name;
city.appendChild(option);
}
}
}
//选择城市后,初始化地区数据
city.onchange = function(){
var pIndex = province.selectedIndex;
var cIndex = this.selectedIndex;
district.innerHTML = "<option value=''>请选择地区</option>";
if(pIndex!=0 && cIndex!=0){
var districtData = areaData[pIndex-1].city[cIndex-1].district;
for(var i=0;i<districtData.length;i++){
var option = document.createElement("option");
option.innerText = districtData[i];
district.appendChild(option);
}
}
}
```
这段代码通过读取一个包含省市区数据的数组`areaData`,实现了省市区三级联动的功能。用户选择省份后,会根据所选省份的下标在`areaData`数组中找到对应的城市数据,再将城市数据添加到城市选择框中;用户选择城市后,会根据所选省份和城市的下标找到对应的地区数据,再将地区数据添加到地区选择框中。
阅读全文