javascript实现二级联动列表
<!DOCTYPE HTML>
<html>
<head>
<title>二级联动列表</title>
<meta charset="utf-8" />
<style>
.hide {
display: none;
}
</style>
</head>
<body>
<select name="provs">
<option>—选择省—</option>
<option>北京市</option>
<option>天津市</option>
<option>河北省</option>
</select>
<select name="cities" class="hide">
</select>
<script>
var cities = [
[{ "name": '东城区', "value": 101 },
{ "name": '西城区', "value": 102 },
{ "name": '海淀区', "value": 103 },
{ "name": '朝阳区', "value": 104 }],
[{ "name": '河东区', "value": 201 },
{ "name": '河西区', "value": 202 },
{ "name": '南开区', "value": 303 }],
[{ "name": '石家庄市', "value": 301 },
{ "name": '廊坊市', "value": 302 },
{ "name": '保定市', "value": 303 },
{ "name": '唐山市', "value": 304 },
{ "name": '秦皇岛市', "value": 304 }]
];
var provs=document.getElementsByName("provs")[0];
provs.onchange=function(){
var city=document.getElementsByName("cities")[0];
if(this.selectedIndex==0){
city.className="hide";
return;
}
city.innerHTML="";
var i=this.selectedIndex-1;
var frag=document.createDocumentFragment();
var option=document.createElement("option");
option.innerHTML="-选择市-";
frag.appendChild(option);
for(var ct of cities[i]){
var option=document.createElement("option");
option.innerHTML=ct.name;
frag.appendChild(option);
}
city.appendChild(frag);
city.className="";
}
</script>
</body>
</html>