需求概况如下:点击某个文件夹,显示该文件夹下的子文件夹。文件夹的层级和数量不固定。
在这里,我简单准备了一下数据结构,来模拟这个效果:
var nodes=[ ???{ ???????id: 1, ????????pid: 0, ????????name: "1-1", ????????children: [ ???????????{ ???????????????id: 11, ????????????????pid: 1, ????????????????name: "1-1-1", ????????????????children: [ ???????????????????{ ???????????????????????id: 111, ????????????????????????pid: 11, ????????????????????????name: "1-1-1-1", ????????????????????????children: [ ???????????????????????????{ ???????????????????????????????id: 1111, ????????????????????????????????pid: 111, ????????????????????????????????name: "1-1-1-1-1", ????????????????????????????????children: [ ] ???????????????????????????} ???????????????????????] ???????????????????}, ????????????????????{ ???????????????????????id: 112, ????????????????????????pid: 11, ????????????????????????name: "1-1-1-2", ????????????????????????children: [ ] ???????????????????} ???????????????] ???????????} ???????] ???}, ????{ ???????id: 2, ????????pid: 0, ????????name: "1-2", ????????children: [ ???????????{ ???????????????id: 22, ????????????????pid: 2, ????????????????name: "1-2-1", ????????????????children: [ ] ???????????} ???????] ???}]
代码实现:
var n=0;
function znode(arr){
var str=‘‘
var childrenstr=‘‘
n++;
var m=0;
$.each(arr,function(index,item){
m++;
childrenstr+=‘<div class="children‘+m+‘">‘+item.name+‘</div>‘;//代表第n级第m个子集
$(‘body‘).on(‘click‘,‘.level‘+n+‘ .children‘+m+‘‘,function(){
if(item.children.length>0){
znode(item.children)//点击某个子集,递归循环对应的数组,获取子子集
}else{
alert(‘没有子集了‘)
}
})
})
str=‘<div class="level‘+n+‘">‘+childrenstr+‘</div>‘//代表第n级
$(‘body‘).html(str);
};
znode(nodes)
效果如下:
点击1-1后,展示1-1的子集如下
js递归渲染子节点(点击父节点展示子节点)
原文地址:http://www.cnblogs.com/nancyzn/p/7978157.html