<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>省份城市的三级联动</title>
</head>
<body>
<select id="province">
<option value="-1">请选择</option> <!-- 由于数组下标从0开始,因此这里的value属性设为-1,避免将其识别为某个地区 -->
</select>
<select id="city"></select>
<select id="country"></select>
<script type="text/javascript">
var provinceArr = ['上海','江苏','河北'];
var cityArr = [
['上海市'],
['苏州市','南京市','扬州市'],
['石家庄','秦皇岛','张家口']
];
var countryArr = [
[
['黄浦区','静安区','长宁区','浦东区']
],[
['虎丘区','吴中区','相城区','姑苏区','吴江区'],['玄武区','秦淮区','建邺区','鼓楼区','浦口区'],['邗江区','广陵区','江都区']
],[
['长安区','桥西区','新华区','井陉矿区'],['海港区','山海关区','北戴河区','抚宁区'],['桥东区','桥西区','宣化区','下花园区']
]
];
// 省份下拉菜单
function createOption(obj, data){
for(var i in data){
var op = new Option(data[i], i);
obj.options.add(op);
}
}
var province = document.getElementById('province');
createOption(province,provinceArr);
//城市下拉菜单
var city = document.getElementById('city');
province.onchange = function() {
city.options.length = 0;
createOption(city,cityArr[province.value]);
};
//区域下拉菜单
var country = document.getElementById('country');
city.onchange = function(){
country.options.length = 0;
createOption(country,countryArr[province.value][city.value]);
}
//修改省份province的onchange事件
province.onchange = function() {
city.options.length = 0;
createOption(city, cityArr[province.value]);
if (province.value >= 0) {
city.onchange(); //自动添加城市对应区域下拉菜单
} else {
country.options.length = 0; //清空country下的原有option
}
};
</script>
</body>
</html>
效果图:
|