内容
通过三个下拉菜单的联动来实现,第一级下拉菜单为省级,第二级下拉菜单为市级,第三级下拉菜单为区级。当点击第一级下拉菜单,第二级菜单的内容会自动匹配;选择第二级菜单时,第三级菜单会自动生成。当我取消上一级菜单的选项时,次一级选项会自动消失。
原理
先定义这三个省市区数组
然后定义默认索引,再以一个for循环添加省份选择的内容,创建函数根据索引进行填入对应的内容
html
<body>
<form>
<select id="province">
<option>请选择所在省份</option>
</select>
<select id="city">
<option>请选择所在城市</option>
</select>
<select id="quxian">
<option>请选择所在区县</option>
</select>
</form>
</body>
js
<script>
var arr_province = ["江苏", "安徽", "福建"];
var arr_city = [
["南京", "无锡", "徐州"],
["合肥", "芜湖","滁州"],
["福州", "厦门"]
]
var arr_quxian = [
[
["玄武区","秦淮区","鼓楼区","浦口区"],
["锡山区","惠山区","滨湖区","梁溪区"],
["云龙区","泉山区","贾汪区","铜山区"],
],
[
["瑶海区", "庐阳区", "蜀山区", "包河区"],
["镜湖区", "鸠江区", "湾沚区", "繁昌区"]
],
[
["鼓楼区", "台江区", "沧山区", "马尾区"],
["吴兴区","南浔区","德清县","长兴区"]
]
];
var province = document.getElementById("province");
var city = document.getElementById("city");
var quxian = document.getElementById("quxian");
var proIndex = -1; // 所选省份的默认索引
for(var i = 0; i < arr_province.length; i++) {
province.options.add(new Option(arr_province[i]));
}
province.onchange = function getCity() {
// 每次选择省份先清空市和区县的列表
city.options.length = 1;
quxian.options.length = 1;
// 获取所选省份的索引
proIndex = this.selectedIndex - 1;
// 如果所选省份的索引不是0(默认选项),则填入对应市的内容
if(proIndex > -1) {
for(var i = 0; i < arr_city[proIndex].length; i++) {
city.options.add(new Option(arr_city[proIndex][i]));
}
}
}
city.onchange = function getQuxian() {
quxian.options.length = 1;
var cityIndex = this.selectedIndex - 1;
if(cityIndex > -1) {
for(var i = 0; i < arr_quxian[proIndex][cityIndex].length; i++) {
quxian.options.add(new Option(arr_quxian[proIndex][cityIndex][i]));
}
}
}
</script>
运行
三联下拉菜单