简体   繁体   English

使用D3将分层JSON转换为HTML

[英]Transforming hierarchical JSON to HTML using D3

I am trying to visualize hierarchical JSON using D3 using recursive function. 我试图通过递归函数使用D3可视化分层JSON。 Here is JSFiddle – http://jsfiddle.net/nBVcs/ and here is relevant part of the code: 这是JSFiddle – http://jsfiddle.net/nBVcs/ ,这是代码的相关部分:

function addNode(selection) {
   var nodeGroup = selection.selectAll('.child')
       .data(function(d) { return d.children })

   nodeGroup
       .enter()
       .append('div')
       .attr("class", "child")

   nodeGroup
       .exit()
       .remove()

   nodeGroup
       .style("padding-left", "2em")

   nodeGroup.append("text")
       .text(function(d) { return d.name });

    nodeGroup.each(function(d) {
        if (d.children) {
            nodeGroup.call(addNode)
        };
    });
}

So far, this approach has several problems. 到目前为止,这种方法有几个问题。 First is that leaf nodes are rendered twice. 首先是叶节点被渲染两次。

Another issue with this approach is that adding deeper leaf nodes will lead to error because D3 will try to bind non-existing array (d.children) to the selection. 这种方法的另一个问题是,添加更深的叶节点将导致错误,因为D3将尝试将不存在的数组(d.children)绑定到选择项。

I would be glad if you could point me to the right direction. 如果您能指出正确的方向,我将非常高兴。

Your recursive call was incorrect, this will work: 您的递归调用不正确,这将起作用:

nodeGroup.each(function(d) {
    if (d.children) {
        d3.select(this).call(addNode);
    };
});

I also updated your fiddle . 我还更新了你的小提琴

I made another small modification: The <text> node should be appended to the .enter() group, otherwise it will be duplicated when you update the tree. 我做了另一个小的修改: <text>节点应附加到.enter()组,否则在更新树时将被复制。 (this is only relevant if you plan on using this code not only for creating the tree, but also for updating it) See general update pattern for more information. (这仅在您计划将代码不仅用于创建树,还用于更新树时才有意义)。有关更多信息,请参见常规更新模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM