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


  • 1
  • 2
  • 3
 
<html>
<head>
<meta charset="GB18030">
<title>Insert title heretitle>
<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 = "
    "; $.each(obj, function (index, item) { if (typeof(obj[index]) == "object") { str += "
  • " + index; str += buildMenu(obj[index]); //递归判断是不是object,直到不是li str += "
  • "
    ; } else { // alert(index + "--" + obj[index]); //item == obj[index] str += "
  • " + index + "
  • "
    } }); str += "
"
; 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

效果如下: 
jquery+递归自动生成无限级菜单_第1张图片

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

你可能感兴趣的:(jquery+递归自动生成无限级菜单)