如何从这个d3.js layout.tree中获取树祖先和树后代的列表?

时间:2016-05-18 07:28:54

标签: javascript angularjs d3.js tree

我正在尝试和修改d3.js的this示例,以根据JSON树结构绘制树。这就是树的一部分开头:

我正在尝试进行两次单独的修改,但我不知道该怎么做:

  1. 单击节点的文本时,我想获取所有树后代的文本元素的集合。我想这样做,以便我可以在my-old-classmy-new-class之间切换他们的样式类。
  2. 单击节点的文本时,我想获得所有树祖先的文本元素的集合。我想这样做,以便我可以在my-old-classmy-new-class之间切换他们的样式类。
  3. 我该怎么做?

    除了我需要在nodeEnter.append("text")语句中添加一个on-click函数之外,我根本不知道怎么做#1。但是这个功能应该做什么?

    对于#2,我知道这是我需要修改的代码的相关部分。像这样:

    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; })
      .style("fill-opacity", 1e-6)
      .on("click", function(d) {
            for (var currentAncestor = this.parentNode; /* WHAT EXPRESSION GOES HERE?? */; currentAncestor = currentAncestor.parentNode) {
                var ancestorText = /* WHAT EXPRESSION GOES HERE?? */;
                ancestorText.classed("my-new-class", !ancestorText.classed("my-new-class"));
                ancestorText.classed("my-old-class", !ancestorText.classed("my-old-class"));
      });
    

    但是我不知道该替换这两个表达式是什么,以便我正确地循环遍历树的祖先(不是DOM祖先!!)的文本元素

    修改

    例如,在下面的屏幕截图中,当用户点击文本“数据”时,我希望其祖先文本(“vis”和“flare”)及其后代文本(出现在右侧的每个单词) “数据”变成红色)

    enter image description here

1 个答案:

答案 0 :(得分:2)

每个节点应该有这样的父节点:

  function collapse(d) {
    if (d.children) {
      d.children.forEach(function(child){
        child.parent = d;//so now each node will have a parent except root node.
      });      
      d._children = d.children;
      d._children.forEach(collapse);
      d.children = null;
    }
  }

接下来设置颜色的功能。 此函数将遍历给定节点并将其子项设置为具有颜色字段。

function setColor(d, color) {
  d.color= color;
  if (d.children) {
    d.children.forEach(function(d){setColor(d,color)});
  } else if(d._children){
    d._children.forEach(function(d){setColor(d,color)});
  }
}

在文本上单击调用此函数:

function textClick(d) {
  setColor(root, "black");//set all the nodes to have black.
  d1 = d;
  //iterate over all its parent and make it red
  while(d1){
    d1.color = "red";
    d1 = d1.parent;
  }
  //set color of the children node to red.
  setColor(d, "red")
  update(root);//call update so that the node text color is colored accordingly.
}

工作代码here