JS实现省市区三级联动(json假数据)
// 假设的JSON数据
var provinceData = [
{
"name": "北京市",
"city": [
{
"name": "北京市",
"area": ["东城区", "西城区", "朝阳区", "丰台区", "石景山区", "海淀区", "门头沟区", "房山区", "通州区", "顺义区", "昌平区", "大兴区", "怀柔区", "平谷区", "密云区", "延庆区"]
}
]
},
// ... 其他省份数据
];
// 初始化省份、城市和区域的选择菜单
function initSelect(provinceData) {
var provinceSelect = document.getElementById('province');
var citySelect = document.getElementById('city');
var areaSelect = document.getElementById('area');
// 清空选择菜单
provinceSelect.innerHTML = '';
citySelect.innerHTML = '';
areaSelect.innerHTML = '';
// 添加省份选项
provinceData.forEach(function(province) {
var option = document.createElement('option');
option.value = province.name;
option.text = province.name;
provinceSelect.appendChild(option);
});
// 为省份选择菜单添加变更事件监听
provinceSelect.addEventListener('change', function() {
var provinceName = this.value;
var cities = provinceData.find(function(item) {
return item.name === provinceName;
}).city;
// 清空城市和区域选项
citySelect.innerHTML = '';
areaSelect.innerHTML = '';
// 添加城市选项
cities.forEach(function(city) {
var option = document.createElement('option');
option.value = city.name;
option.text = city.name;
citySelect.appendChild(option);
});
});
// 为城市选择菜单添加变更事件监听
citySelect.addEventListener('change', function() {
var cityName = this.value;
var areas = provinceData.find(function(item) {
return item.name === provinceSelect.value;
}).city.find(function(city) {
return city.name === cityName;
}).area;
// 添加区域选项
areas.forEach(function(area) {
var option = document.createElement('option');
option.value = area;
option.text = area;
areaSelect.appendChild(option);
});
});
}
// 初始化数据
initSelect(provinceData);
这段代码使用了现代JavaScript语法,包括用于数组和对象的find
方法,以及箭头函数。代码中的initSelect
函数负责初始化选择菜单,并设置相应的事件监听器来处理省市区的级联效果。这个例子使用了一个假设的\`provin
评论已关闭