显示折叠树中的子项数

时间:2014-07-03 12:58:05

标签: javascript d3.js

我正在使用mbostock' s Collapse tree

enter image description here

我需要在每个节点中显示孩子的数量以及节点名称,例如" flare(10)"," analytics(3)"。

我尝试过使用......

  nodeEnter.append("text")
  .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
  .attr("dy", ".35em")
  .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
  .text(function(d) { return d.name + " (" + d.children.length() + ")"; })
  .style("fill-opacity", 1e-6);

但这似乎不起作用。如何让儿童计算节点?

1 个答案:

答案 0 :(得分:2)

您已走上正轨,但您的代码存在两个问题。

  1. 长度是Javascript中数组的属性,因此您无需使用括号即可访问它:

    >>> L = [ 1, 2, 3 ]
    >>> L.length
    3
    
  2. 您需要考虑以下事实:某些节点d具有d.children,某些节点具有d._children,而某些节点根本没有子节点。尝试这样的事情:

    .text(function(d) {
        var numChildren = 0;
        if (d.children) numChildren = d.children.length;
        else if (d._children) numChildren = d._children.length;
        return d.name + " (" + numChildren + ")";
    })
    
  3. 这就是你得到的:

    enter image description here