• 使用递归算法实现树菜单


    这个是后台管理的动态创建的菜单,比较难,不过,仔细揣摩还是比较简单的,所以,直接上代码。

    <!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='
    <ul >
    ';
    			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>
    ';
    
            };
    
            html+='</ul>
    ';
    
            return html;
    	}
    };
    	var html=new treeMenu(zNodes).init(0);
    	$("#div").html(html);
    	</script>
    </body>
    </html>
    

      配上这张图看代码的话,可能更加好理解这段代码。

    下面这一种和前一种的区别就是他们的数据结构不一样,导致实现代码的逻辑也不一样。不过,下面这一种方式复杂的工作全部交给了后台,基本上没有前端什么事情了。

  • 相关阅读:
    多项式大合集
    【题解】Codeforces 961G Partitions
    【题解】Counting D-sets(容斥+欧拉定理)
    【题解】分特产(组合数+容斥)
    【题解】P4247 [清华集训]序列操作(线段树修改DP)
    【题解】没有上司的舞会
    【题解】数字组合(NTT+组合 滑稽)
    【瞎总结】组合模型及其组合意义的阐释
    P2822 组合数问题——巧用前缀和
    P3239 [HNOI2015]亚瑟王——概率DP
  • 原文地址:https://www.cnblogs.com/myprogramer/p/10303275.html
Copyright © 2020-2023  润新知