简单易懂的js代码
//适合新手 ps:本人也是新手
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>省市县三级菜单</title>
<script>
var arrSheng = new Array("湖南省", "湖北省", "浙江省");
var arrShi = new Array(
new Array("长沙市", "株洲市", "湘潭市"),
new Array("武汉市", "荆州市", "宜昌市"),
new Array("杭州市", "宁波市", "温州市")
);
var arrQu = new Array(
new Array(
new Array("岳麓区", "芙蓉区", "天心区", "开福区"),
new Array("芦淞区", "荷塘区", "石峰区", "天元区", "云龙区"),
new Array("岳塘区", "雨湖区", "九华区")
),
new Array(
new Array("武昌区", "汉阳区", "青山区"),
new Array("荆州区", "沙市区"),
new Array("夷陵区", "西陵区", "伍家岗区")
),
new Array(
new Array("上城区", "下城区", "江干区", "拱墅区","西湖区","滨江区","萧山区","余杭区","富阳区"),
new Array("海曙区", "江北区", "北仑区", "镇海区", "鄞州区", "奉化区"),
new Array("鹿城区", "龙湾区","瓯海区", "洞头区")
)
);
//添加省
function addSheng() {
sheng.length = 1;
for(i = 0; i < arrSheng.length; i++) {
sheng.add(new Option(arrSheng[i]));
}
}
//添加市
function addShi() {
//已选择的省对应的市的数组
var nowShi = arrShi[sheng.selectedIndex - 1];
shi.length = 1;
for(i = 0; i < nowShi.length; i++) {
shi.add(new Option(nowShi[i]));
}
}
//添加区
function addQu() {
//已选择的省(三维数组的一维索引)
var lv1 = sheng.selectedIndex - 1;
//已选择的市(三维数组的二维索引)
var lv2 = shi.selectedIndex - 1;
//已选择的省和市对应的区的数组
var nowQu = arrQu[lv1][lv2];
qu.length = 1;
for(i = 0; i < nowQu.length; i++) {
qu.add(new Option(nowQu[i]));
}
}
//添加省
function show() {
var choose1 = sheng.selectedIndex - 1;
var choose2 = shi.selectedIndex - 1;
var choose3 = qu.selectedIndex - 1;
showResult.innerHTML =arrSheng[choose1] +" "+ arrShi[choose1][choose2] + " "+arrQu[choose1][choose2][choose3];
}
</script>
</head>
<body onload="addSheng();">
<select id="sheng" onchange="addShi();">
<option value="-1">-省-</option>
</select>
<select id="shi" onchange="addQu();">
<option value="-1">-市-</option>
</select>
<select id="qu" onchange="show();">
<option value="-1">-区-</option>
</select>
<div id="showResult"></div>
</body>
</html>