前几天在看js的相关内容,所以就简单写了一个二级联动菜单。分享一下。
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>JS实现二级联动菜单</title>
6 </head>
7 <body>
8 <form name="form1" method="post" action="">
9 省份:<select name="province" id="province" onchange="changeSelect(this.selectedIndex)"></select>
10 地区:<select name="city" id="city"></select>
11
12 </form>
13 </body>
14 </html>
15 <script type="text/javascript">
16 var arr_province = ["请选择省/城市","北京市","上海市","天津市","重庆市","深圳市","广东省"];
17 var arr_city = [
18 ["请选择城市/地区"],
19 ["东城区","西城区","朝阳区","宣武区","昌平区","大兴区","丰台区","海淀区"],
20 ['宝山区','长宁区','丰贤区', '虹口区','黄浦区','青浦区','南汇区','徐汇区','卢湾区'],
21 ['和平区', '河西区', '南开区', '河北区', '河东区', '红桥区', '塘古区', '开发区'],
22 ['俞中区', '南岸区', '江北区', '沙坪坝区', '九龙坡区', '渝北区', '大渡口区', '北碚区'],
23 ['福田区', '罗湖区', '盐田区', '宝安区', '龙岗区', '南山区', '深圳周边'],
24 ['广州市','惠州市','汕头市','珠海市','佛山市','中山市','东莞市']
25 ];
26 //网页加载完成,初始化菜单
27 window.onload = init;//传入函数地址
28 function init(){
29 //首先获取对象
30 var province = document.form1.province;
31 var city = document.form1.city;
32
33 //指定省份中<option>标记的个数
34 province.length = arr_province.length;
35
36 //循环将数组中的数据写入<option>标记中
37 for(var i=0;i<arr_province.length;i++){
38 province.options[i].text = arr_province[i];
39 province.options[i].value = arr_province[i];
40 }
41
42 //修改省份列表的默认选择项
43 var index = 0;
44 province.selectedIndex = index;
45
46 //指定城市中<option>标记的个数
47 city.length = arr_city[index].length;
48
49 //循环将数组中的数据写入<option>标记中
50 for (var j = 0; j<arr_city[index].length;j++) {
51 city.options[j].text = arr_city[index][j];
52 city.options[j].value = arr_city[index][j];
53 }
54
55 }
56
57 function changeSelect(index){
58 //选择对象
59 var city = document.form1.city;
60 //修改省份列表的选择项
61 province.selectedIndex = index;
62
63 //指定城市中<option>标记的个数
64 city.length = arr_city[index].length;
65
66 //循环将数组中的数据写入<option>标记中
67 for (var j = 0; j<arr_city[index].length;j++) {
68 city.options[j].text = arr_city[index][j];
69 city.options[j].value = arr_city[index][j];
70 }
71 }
72
73 </script>