下面是一段js实现二级联动菜单的代码,供初学者使用。文件名:index.html,代码如下
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- <script type="text/javascript">
- var arr_province = ["请选择省/城市","北京市","上海市","天津市","重庆市","深圳市","广东省"];
- var arr_city = [
- ["请选择城市/地区"],
- ["东城区","西城区","朝阳区","宣武区","昌平区","大兴区","丰台区","海淀区"],
- ['宝山区','长宁区','丰贤区', '虹口区','黄浦区','青浦区','南汇区','徐汇区','卢湾区'],
- ['和平区', '河西区', '南开区', '河北区', '河东区', '红桥区', '塘古区', '开发区'],
- ['俞中区', '南岸区', '江北区', '沙坪坝区', '九龙坡区', '渝北区', '大渡口区', '北碚区'],
- ['福田区', '罗湖区', '盐田区', '宝安区', '龙岗区', '南山区', '深圳周边'],
- ['广州市','惠州市','汕头市','珠海市','佛山市','中山市','东莞市']
- ];
- //网页加载完成,初始化二级菜单
- window.onload = init; //传地址,不带括号
- function init()
- {
- //获取name=province和name=city的对象
- var province = document.form1.province;
- var city = document.form1.city;
- //指定省份下拉中<option>标记的个数
- province.length = arr_province.length;
- //循环将arr_province中的数据写入到<option>标记中
- for(var i=0;i<arr_province.length;i++)
- {
- province.options[i].text = arr_province[i];
- province.options[i].value = arr_province[i];
- }
- //修改省份列表中默认选择项
- var index = 0;
- province.selectedIndex = index;
- //指定城市下拉中<option>标记的个数
- city.length = arr_city[index].length;
- //循环将arr_city中对应的数据写入到<option>标记中
- for(var j=0;j<arr_city[index].length;j++)
- {
- city.options[j].text = arr_city[index][j];
- city.options[j].value = arr_city[index][j];
- }
- }
- function changeSelect(index)
- {
- //获取name=city的对象
- var city = document.form1.city;
- //指定城市下拉中<option>标记的个数
- city.length = arr_city[index].length;
- //循环将arr_city中对应的数据写入到<option>标记中
- for(var j=0;j<arr_city[index].length;j++)
- {
- city.options[j].text = arr_city[index][j];
- city.options[j].value = arr_city[index][j];
- }
- }
- </script>
- </head>
- <body>
- <form name="form1" method="post" action="login.php">
- 省份:<select name="province" onchange="changeSelect(this.selectedIndex)"></select>
- 城市:<select name="city"></select>
- </form>
- </body>
- </html>
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏