首页 > 建站教程 > JS、jQ、TS >  简单的js联动菜单示例正文

简单的js联动菜单示例

联动菜单,即点击上一级菜单,通过ajax方法,加载这个菜单的对应列表,显示到下一级菜单上。这个联动菜单一般都是需要和后台交换数据,并且一般会用到ajax异步刷新技术,如果数据比较大,存储在数据库或其他文件的话。本例比较简单,就是定义两个数组,第一个数组中的每个内容对应第二个二维数组中的子数组。明白本例的原理,也可以使用在数据比较少,可以直接放在js文件中的案例。代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>简单的js联动菜单示例 - 我爱模板网 www.5imoban.net</title>
<script>
    //定义两组数据
    var city =["北京","上海","合肥","吉林"];
    var area = [
        ["东城","西城","海淀","朝阳","丰台","门头沟","石景山","房山","通州","顺义","昌平","大兴","怀柔","平谷","延庆","密云"],
        ["黄浦","徐汇","长宁","静安","普陀","虹口","杨浦","闵行","宝山","嘉定","浦东","金山","松江","青浦","奉贤","崇明"],
        ["瑶海区","庐阳区","蜀山区","包河区","长丰县","肥东县","肥西县","庐江县","巢湖市","合肥高新技术产业开发区","合肥经济技术开发区","合肥新站综合试验区","巢湖经济开发区"],
        ["朝阳区","南关区","二道区","宽城区","绿园区","双阳区","榆树市","九台市","德惠市","农安县"]
    ]
  window.onload=function(){
      loadCity(); //为第一个select填充内容
      document.getElementById("city").onchange = loadArea;    
    };
    //读取城市数据,并且填充到select中
    function loadCity(){
        var oCity= document.getElementById("city");
        for(var i in city){
            var op =new Option(city[i],city[i]);
            oCity.options.add(op)
        };
    };
    //通过获取被选中的城市的option的索引值,找到对应的区域的索引值,并且遍历出来放到区域的select中
    function loadArea(){
        var index = document.getElementById("city").selectedIndex;
        var oArea = document.getElementById("area");
        oArea.options.length=0;
        for(var i in area[index]){
            var op= new Option(area[index][i],area[index][i])
            oArea.options.add(op)
        }
    }
</script>
</head>
<body>
城市:<select id="city"></select>&nbsp;区域:<select id="area"></select>
</body>
</html>