码迷,mamicode.com
首页 > Web开发 > 详细

js中实现无限层级的树形结构(类似递归)

时间:2019-01-22 14:21:42      阅读:402      评论:0      收藏:0      [点我收藏+]

标签:逻辑   就是   1.4   doctype   highlight   代码   ini   ups   pid   

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

<!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>

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

技术分享图片

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

有兴趣的童鞋可以到我的微信公众号里面查看

代码地址,我放这儿了:

https://mp.weixin.qq.com/s/ccgTHxpZoY2mMq8-Pmgtuw

 

js中实现无限层级的树形结构(类似递归)

标签:逻辑   就是   1.4   doctype   highlight   代码   ini   ups   pid   

原文地址:https://www.cnblogs.com/myprogramer/p/10303275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!