用js写省市县三级联动
时间: 2023-08-18 18:10:52 浏览: 42
好的,下面是一个使用纯JavaScript实现省市县三级联动的示例代码:
HTML部分:
```html
<select id="province"></select>
<select id="city"></select>
<select id="county"></select>
```
JavaScript部分:
```javascript
// 获取省份数据
function getProvinces() {
return [
{ name: '北京市', cities: [{ name: '北京市' }] },
{ name: '上海市', cities: [{ name: '上海市' }] },
{ name: '江苏省', cities: [{ name: '南京市' }, { name: '苏州市' }, { name: '无锡市' }] },
// 其他省份数据...
];
}
// 获取城市数据
function getCities(provinceName) {
// 根据省份名称获取对应的城市数据
// 省份名称和城市数据可以通过接口或其他方式获取
// 此处为示例数据,需要根据实际情况进行修改
const provinces = getProvinces();
const province = provinces.find(p => p.name === provinceName);
return province ? province.cities : [];
}
// 获取县区数据
function getCounties(cityName) {
// 根据城市名称获取对应的县区数据
// 城市名称和县区数据可以通过接口或其他方式获取
// 此处为示例数据,需要根据实际情况进行修改
// 返回一个空数组表示没有县区数据
return [];
}
// 填充下拉框选项
function fillOptions(element, options) {
element.innerHTML = '';
for (let option of options) {
const optionElement = document.createElement('option');
optionElement.value = option.name;
optionElement.textContent = option.name;
element.appendChild(optionElement);
}
}
// 省份下拉框改变事件
document.getElementById('province').addEventListener('change', function() {
const selectedProvince = this.value;
const cities = getCities(selectedProvince);
fillOptions(document.getElementById('city'), cities);
fillOptions(document.getElementById('county'), []);
});
// 城市下拉框改变事件
document.getElementById('city').addEventListener('change', function() {
const selectedCity = this.value;
const counties = getCounties(selectedCity);
fillOptions(document.getElementById('county'), counties);
});
// 初始化省份下拉框
const provinces = getProvinces();
fillOptions(document.getElementById('province'), provinces);
```
上述代码使用两个函数`getProvinces()`和`getCities()`来获取省份和城市数据,其中的数据可以根据实际情况自行修改。`getCounties()`函数用于获取县区数据,此处为示例代码,返回一个空数组表示没有县区数据。`fillOptions()`函数用于将数据填充到对应的下拉框中。最后,通过监听省、市下拉框的change事件来进行相应的数据更新。