Javascript 三级联动
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>三级联动</title>
</head>
<body>
省<select name="pro" onchange="showCity()">
<!-- <option value="1">北京</option> -->
</select>
市<select name="city" onchange="showArea()">
<option value="0">请选择</option>
</select>
区<select name="area">
<option value="0">请选择</option>
</select>
<script type="text/javascript">
var pros=["请选择","北京","上海","广东","重庆"];
var citys=[
["请选择"],
["朝阳区","昌平","东城"],
["闸北区","宝山"],
["广州","东莞"],
["渝北","九龙坡"],
];
var areas=[
["请选择"],
[["大前门","小前门"],["时尚","小鸟","西单"],["门前","门后"]],
[["大宁","大宁1"],["宝山1","宝山2","宝山3"]],
[["广州1","广州2"],["东莞1","东莞2"]],
[["渝北1","渝北2"],["九龙坡1","九龙坡2"]]
]
//取省这个select
var pro=document.getElementsByName("pro")[0];
//添加省
for(var i in pros){
//创建option
var opt=document.createElement("option");
//设置option的属性和文本
opt.value=i;
opt.innerHTML=pros[i];
//添加到select中
pro.appendChild(opt);
}
//省被改变时,更新城市
function showCity(){
//先检查事件是否有效
//alert('sssss');
//取省这个select
//var pro=document.getElementsByName("pro")[0];
var city=document.getElementsByName("city")[0];
//去掉已有的option,只保留第一个
//alert(city.options.length);
city.options.length=1;
//当前选择的value值
//alert(pro.value);
// 去城市数组中,找对应下标的数组
var cityData=citys[pro.value]
for(var i in cityData){
var opt=document.createElement("option");
opt.value=parseInt(i)+1;
opt.innerHTML=cityData[i];
city.appendChild(opt);
}
}
//市被改变时,更新区
function showArea(){
//alert("aaaa");
//1.取到这个select
var city=document.getElementsByName("city")[0];
var area=document.getElementsByName("area")[0];
//去掉已有的option,只保留第一个
//alert(city.options.length);
area.options.length=1;
//当前选择的value值
//alert(city.value);
//去区的数组中,找相对应的下标数组
var areaData=areas[pro.value][city.value-1];
alert(areaData);
//alert(city.value);
for(var i in areaData){
var opt=document.createElement("option")
opt.value=parseInt(i)+1;
opt.innerHTML=areaData[i];
area.appendChild(opt);
}
}
</script>
</body>
</html>