d3.js:构建树状嵌套HTML结构。关闭问题

时间:2015-09-28 11:19:16

标签: javascript recursion d3.js tree

我需要用树状数据构建嵌套的HTML结构,跟踪从root开始的每个节点的路径(为了到达特定节点而必须遍历的所有节点的名称数组)。我已经创建了一个可以很好地构建html的递归函数,但是跟踪路径不起作用。

我试图通过在每个步骤中使用节点名称填充数组来完成此操作,但存储了错误的值。我怀疑它可能是js封闭陷阱,但不确定。这是功能:

// parent - d3 selection, path - array of parent nodes
function buildTreeRecursively(parent, path) {

    // start from empty if it's root and no array passed
    path = path || []; 

    // populate array with this node's namme
    path.push(parent.datum().name);

    if (!parent.datum().children) return;

    parent.append("div")
        .style('padding-left', path.length * 10 + 'px')
        .text(function(d) { 
            // I'm printing the path here so the you can see the error
            return d.name + ": (" +  path.join(" -> ") + ")" 
        })
        .attr("path", function(d) {
            return path.join(" ")
        }) 
        .selectAll("div")
        .data(function(d) { return d.children || [] })
        .enter()
        .append("div")
        .call(function(selection) {
            return buildTreeRecursively(selection, path);
        });
}

这里是jsFiddle - http://jsfiddle.net/g6hgkeh9/2/

0 个答案:

没有答案
相关问题