2016-11-24 1 views
4

この配列データを使用してdivベースのツリーレイアウトを動的に生成しようとしています。jsonデータから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データを反復して

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(); 

以下のコードを使用して、ツリーベースのHTMLをcreting午前問題は、私は適切にdiv要素の名前を付けることができないですので、添付のロジックがうまくいかないです。誰でも何を変更する必要があるのか​​を提案できますか?

私はまた、参照https://jsfiddle.net/birju112/2wL512bs/1/

答えて

1

ためjsfiddleを添付しています私はあなたの次のノード・レンダリング機能を示唆しています。あなたのような再帰的なものですが、そのロジックを "単純化"する外部変数は使用しません。すべての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); 
+0

感謝。 –

関連する問題