js遞歸渲染子節點(點擊父節點展示子節點)
阿新 • • 發佈:2017-12-04
ner container com 循環 cnblogs each ber 獲取 r+
需求概況如下:點擊某個文件夾,顯示該文件夾下的子文件夾。文件夾的層級和數量不固定。
在這裏,我簡單準備了一下數據結構,來模擬這個效果:
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遞歸渲染子節點(點擊父節點展示子節點)