jquery+递归自动生成无限级菜单

 
 
  • 1
  • 2
  • 3
 <!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>Insert title here</title>
<style type="text/css">
    #menu {border: 1px solid black; }
    #menu li {list-style: none;}
    #menu li ul {display: none;}
</style>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //创建类,采用键值对的方式 
        var obj = {"menu1":"a", "menu2":{"item1":"bb","item2":"cc"}, "menu3":{"item1":"aa","item2":"bb","item3":{"button1":"b1","button2":"b2"}}};
        buildMenu(obj);
        $("#menu").html(buildMenu(obj));
        $("#menu ul li").click(function () {
            $(this).siblings().find("ul").css("display", "none"); //找到同一级的ul将其隐藏 
            if ( $(this).has("ul").length > 0 ) {
                $(this).children("ul").css("display", "block");   //如果是ul将其子项显示出来 
            }
        });
    });
    //创建按钮
    function buildMenu(obj) {
        var str = "<ul>";
        $.each(obj, function (index, item) {
            if (typeof(obj[index]) == "object") {
                str += "<li>" + index;
                str += buildMenu(obj[index]); //递归判断是不是object,直到不是li 
                str += "</li>";
            }
            else {
            //  alert(index + "--" + obj[index]);  //item == obj[index]
                str += "<li>" + index + "</li>" 
            }
        });
        str += "</ul>";
        return str;
    }
</script>
</head>
<body>
    <div id="menu"></div>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

效果如下: 
这里写图片描述

点击同一级的菜单可以隐藏。修改的话,只需要在obj里面添加,就是可以了。

猜你喜欢

转载自blog.csdn.net/qmdweb/article/details/80734475