首页 > 代码库 > 级联菜单

级联菜单

利用二维数组和jQuery实现级联菜单,代码如下:

1.html代码

<div class="form_class">
      <label>地址</label>
       <select name="province" id="province></select>
       <select name="city" id="city"></select>
 </div>

2.javascript代码

//第二级菜单数组
var city0=["东城区","西城区","崇文区","宣武区","朝阳区","丰台区","石景山区","海淀区","门头沟区","房山区","通州区","顺义区", "昌平区","大兴区","怀柔区","平谷区","密云县","延庆县","其他"],
    city1=["黄浦区","卢湾区","徐汇区","长宁区","静安区","普陀区","闸北区","虹口区","杨浦区","闵行区","宝山区","嘉定区","浦东新区","金山区","松江区"," 青浦区","南汇区","奉贤区","崇明县","其他"],
    city2=["广州市","清远市","韶关市","河源市","梅州市","潮州市","汕头市","揭阳市","汕尾市","惠州市","东莞市","深圳市","珠海市","中山市","江门市","佛山市","肇庆市","云浮市","阳江市","茂名市","湛江市","其他"],
    city3=["武汉市","十堰市","襄樊市","荆门市","孝感市","黄冈市","鄂州市","黄石市","咸宁市","荆州市","宜昌市","随州市","恩施土家族苗族自治州","仙桃市","天门市","潜江市","神农架林区","其他"];

//第一级菜单数组
var pro=["北京市","上海市","广东省","湖北省"];
//二维数组
var city=[city0,city1,city2,city3];


//第二级菜单
function cityList(num){
            $("#city").html("");
            for(var i=0,len=city[num].length;i<len;i++){
                var citys=$("#city").html();
                $("#city").html(citys+"<option>"+city[num][i]+"</option>");        
            };                
        };
        cityList(0);

       //第一级菜单        
        function proList(){
            for(var i=0,len=pro.length;i<len;i++){
                var pros=$("#province").html();
                $("#province").html(pros+"<option>"+pro[i]+"</option>");        
            };
        };
        proList();

        //第一级菜单change事件        
        $("#province").change(function(){
            var val=$(this).val();
            var num=pro.indexOf(val);
            cityList(num);
        });    

3.效果图如下:

技术分享技术分享

 

级联菜单