我正在尝试使用此数组数据动态生成基于div的树布局.
[{
name: "Asset Cost Allocation",
children:[
{
name:"Child 1",
children: [{
name:"Child 1-1",
children:[
{
name:"Child 1-1-1"
}
]
},{
name:"child 1-2"
}]
},
{
name: "Child 2",
children:[{
name:"Child 2-1",
children:[{
name:"Child 2-1-1"
}]
}]
},
{
name: "Child 3",
children:[
{
name:"Child 3-1"
}
]
}
]
}]
我正在使用下面的代码迭代json数据和基于html的创建树
var branch = {};
var depth = 0;
var rootNode = true;
var pointerBranch;
function renderTree(){
for(var i=0; i< window.data.length; i++){
if(window.data[i].children){
renderRootNode(depth,i,window.data[i]);
}
}
}
function renderRootNode(depth,i,node){
if(rootNode){
$('#wrapper').append("<span class='label'>"+node.name+"</span");
$('#wrapper').append("<div class='branch' id="+i+"-"+depth+"></div>");
pointerBranch = '#'+i+"-"+depth;
rootNode = false;
}else{
branch['branch-'+i+'-'+depth] = true;
$(pointerBranch).append("<div class='entry'><span class='label'>"+node.name+"</span><div class='branch' id="+i+"-"+depth+"></div></div>");
pointerBranch = '#'+i+"-"+depth;
}
depth++;
if(node.children){
for(var a=0;a<node.children.length;a++){
if(node.children[a].children){
renderRootNode(depth,a,node.children[a]);
if(a === node.children.length - 1){
depth -= 2;
pointerBranch = '#'+i+"-"+depth;
}
}else{
$(pointerBranch).append("<div class='entry'><span class='label'>"+node.children[a].name+"</span></div>");
if(a === node.children.length - 1){
depth -= 2;
pointerBranch = '#'+i+"-"+depth;
}
}
}
}
}
renderTree();
问题是我无法正确命名div,因此附加逻辑出错了.任何人都可以建议需要改变什么.
我也附上jsfiddle以供参考https://jsfiddle.net/birju112/2wL512bs/1/
最佳答案 我建议你使用以下节点渲染功能.它是一个像你的递归,但它不使用“简化”其逻辑的外部变量.所有DOM结构都在变量中创建,然后将其添加到页面中.最大的区别是当前元素(指向您的pointerBranch变量)作为参数传递.
function renderNode( node, element, index, depth )
{
var nodeTitle = $("<span/>").addClass( "label" ).text( node.name );
var branch = $("<div/>").addClass( "branch" ).attr( "id", index + "-" + depth );
if( node.children )
{
for( var j = 0 ; j < node.children.length ; j++ )
{
var entry = $("<div/>").addClass( "entry" );
renderNode( node.children[j], entry, j, depth + 1 );
branch.append( entry );
}
}
element.append( nodeTitle ).append( branch );
}
所以renderTree函数中的调用将是:
renderNode( window.data[i], $("#wrapper"), i, 0 );