使用递归算法实现树菜单
这个是后台管理的动态创建的菜单,比较难,不过,仔细揣摩还是比较简单的,所以,直接上代码。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="div"></div> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> var zNodes=[ {code:0,pId:-1,name:"Aaaa"}, {code:1,pId:0,name:"主页"}, {code:11,pId:1,name:"A1"}, {code:111,pId:11,name:"A11"}, {code:12,pId:1,name:"A2"}, {code:13,pId:1,name:"A3"}, {code:2,pId:0,name:"文章管理"}, {code:21,pId:2,name:"用户管理"}, {code:22,pId:2,name:"角色管理"}, {code:23,pId:2,name:"权限管理"}, {code:3,pId:0,name:"C"}, {code:31,pId:3,name:"C1"}, {code:32,pId:3,name:"C2"}, {code:33,pId:3,name:"C3"}, {code:34,pId:31,name:"x"}, {code:35,pId:31,name:"y"}, {code:36,pId:31,name:"z"}, {code:37,pId:36,name:"z1123"}, {code:38,pId:37,name:"z123123123"}, {code:381,pId:38,name:"z1231231234"}, ]; function treeMenu(a){ this.tree=a||[]; this.groups={}; }; treeMenu.prototype={ init:function(pid){ this.group(); return this.getDom(this.groups[pid]); }, group:function(){ for(var i=0;i<this.tree.length;i++){ if(this.groups[this.tree[i].pId]){ //console.log(this.groups[this.tree[i].pId]); this.groups[this.tree[i].pId].push(this.tree[i]); }else{ this.groups[this.tree[i].pId]=[]; this.groups[this.tree[i].pId].push(this.tree[i]); console.log(this.groups[this.tree[i].pId]); } } }, getDom:function(a){ if(!a){return ''} var html='\n<ul >\n'; for(var i=0;i<a.length;i++){ html+='<li><span>'+a[i].name+'</span>'; //html+='<li><a href="#">'+a[i].name+'</a>'; html+=this.getDom(this.groups[a[i].code]); html+='</li>\n'; }; html+='</ul>\n'; return html; } }; var html=new treeMenu(zNodes).init(0); $("#div").html(html); </script> </body> </html>
配上这张图看代码的话,可能更加好理解这段代码。
下面这一种和前一种的区别就是他们的数据结构不一样,导致实现代码的逻辑也不一样。不过,下面这一种方式复杂的工作全部交给了后台,基本上没有前端什么事情了。