简单的纯js三级联动

时间:2024-07-09 17:04:50

参考这个  日尼禾尔  二级联动

写了三级联动

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>三级城市联动</title>
</head>
<body>
<select id="one" onchange="func(this.value)">
<option value="">-请选择省-</option>
<option value="0">浙江省</option>
<option value="1">广东省</option>
<option value="2">福建省</option>
</select>
<select id="two" onchange="funcc()">
<option value="">-请选择市-</option>
</select> <select id="three" >
<option value="">-请选择区-</option>
</select>
</body> <script>
var two = document.getElementById('two'); city = [];//申明   //定义二级数据
city[0] = ['杭州市'];
city[1] = ['广州市','深圳市'];
city[2] = ['厦门市'];
function func(m){
two.length = 1;
   //遍历生产option选项
for (var i = 0; i < city[m].length; i++) {     //创建一个option 把数据存储在option
var op = new Option(city[m][i],i);     //把带有数据的option 添加到第二个select
two.add(op);
};
} dist=[[]];
dist[0]=[[]];
dist[1]=[[]];
dist[2]=[[]];
//定义三级联动
dist[0][0]=['西湖区'];
dist[1][0]=['天河区','番禺区','越秀区'];
dist[1][1]=['南山区','福田区','罗湖区'];
dist[2][0]=['集美区','思明区'];
var three = document.getElementById('three'); function funcc(){
n=document.getElementById("two").selectedIndex;
three.length = 1;
   //遍历生产option选项
m=document.getElementById("one").selectedIndex;
if(m>0) m-=1;
if(n>0)n-=1;
for (var j = 0; j< dist[m][n].length; j++) {     //创建一个option 把数据存储在option
var op = new Option(dist[m][n][j],j);     //把带有数据的option 添加到第二个select
three.add(op);
};
}
</script>
</html>