不多bb,上硬货
html代码
js代码:
var province = document.querySelector(‘#province‘); //省
var cityNode = document.querySelector(‘#city‘); //市
var areaNode = document.querySelector(‘#area‘); //区
// bind 绑定 Province 省份
function bindProvince() {
// option 选项 定义下拉(select)列表中的一个选项(一个条目)
var options = ‘<option value="-1">请选择...</option>‘;
// forEach() 遍历
city_code.forEach(function(c) {
options += `<option value="${c.code}">${c.name}</option>`;
})
province.innerHTML = options
}
bindProvince();
// bind 绑定 City 市
// code 编码
function bindCity(provinceCode) {
var qq = function(v) {
return v.code === provinceCode;
}
// filter() 过滤
var provinceArr = city_code.filter(qq);
var city = [];
if (provinceArr.length > 0) {
var province = provinceArr[0]
city = province.city;
}
var options = ‘<option value="-1">请选择...</option>‘;
var ww = function(c) {
options += `<option value="${c.code}">${c.name}</option>`;
}
city.forEach(ww);
cityNode.innerHTML = options;
}
bindCity("-1");
//绑定 区
function bindArea(provinceCode, cityCode) {
var provinceArr = city_code.filter(function(v) {
return v.code === provinceCode;
});
var area = [];
if (provinceArr.length > 0) {
var province = provinceArr[0]
var cityArr = province.city;
var oneCityArr = cityArr.filter(function(c) {
return c.code === cityCode;
});
if (oneCityArr.length > 0) {
var city = oneCityArr[0];
area = city.area;
}
}
var options = ‘<option value="-1">请选择...</option>‘;
area.forEach(function(c) {
options += `<option value="${c.code}">${c.name}</option>`;
})
areaNode.innerHTML = options;
}
bindArea("-1", "-1")
province.addEventListener(‘change‘, function(e) {
bindCity(e.target.value);
bindArea(e.target.value, "-1")
})
cityNode.addEventListener(‘change‘, function(e) {
var provinceCode = province.value;
var cityCode = e.target.value;
bindArea(provinceCode, cityCode)
})
因为这里需要城市数据,所以我把数据传到码云上了,有需要的小伙伴可以自己去看
链接:https://gitee.com/s272/blog-garden.git