<!-- 省 -->
<select name="province" id="province"> </select>
<!-- 市 -->
<select name="city" id="city"> </select>
<!-- 县 -->
<select name="county" id="county"> </select>
// 数据通常由后台返回,结构如下:
var citys = [
{ "name": "北京", "city": [{ "name": "北京", "area": ["东城区", "西城区", "崇文区", "宣武区", "朝阳区", "丰台区", "石景山区", "海淀区", "门头沟区", "房山区", "通州区", "顺义区", "昌平区", "大兴区", "平谷区", "怀柔区", "密云县", "延庆县"] }] },
{ "name": "天津", "city": [{ "name": "天津", "area": ["和平区", "河东区", "河西区", "南开区", "河北区", "红桥区", "塘沽区", "汉沽区", "大港区", "东丽区", "西青区", "津南区", "北辰区", "武清区", "宝坻区", "宁河县", "静海县", "蓟 县"] }] }
]
// 具体实现
// 获取省
var province = document.getElementById('province');
province.options[0] = new Option('请选择省', -1)
// 获取市
var city = document.getElementById('city');
city.options[0] = new Option('请选择市', -1)
// 获取县
var county = document.getElementById('county');
county.options[0] = new Option('请选择县', -1)
citys.forEach(function (item, index) {
// 添加省
province.options[province.options.length] = new Option(item.name, index);
// 给省绑定事件
province.onchange = function () {
// 获取选择的省
var provinceValue = province.value;
// 首先清空市和区县
city.options.length = 0;
city.options[city.options.length] = new Option('请选择市', -1);
county.options.length = 0;
county.options[county.options.length] = new Option('请选择县', -1)
// 判断是否是‘请选择’
if (province.value !== '-1') {
// 然后给对应的省添加市
citys[provinceValue].city.forEach(function (item, index) {
city.options[city.options.length] = new Option(item.name, index);
// 给市绑定事件
city.onchange = function () {
// 获取选择的市
var cityValue = city.value;
// 清空县
county.options.length = 0;
county.options[county.options.length] = new Option('请选择县', -1);
// 判断选择的市是否是‘请选择’
if (cityValue !== '-1') {
// 设置市对应的县
citys[provinceValue].city[cityValue].area.forEach(function (item, index) {
county.options[county.options.length] = new Option(item, index);
})
}
}
})
}
}
})