单击节点时如何打开子节点的子节点

时间:2016-05-25 17:15:17

标签: d3.js c3.js

我有一个四节点树。我想点击第二个节点,并希望直接打开第四个节点。 意思是我想打开子节点的子节点。 我正在尝试但是无法得到它。

1 个答案:

答案 0 :(得分:0)

https://jsfiddle.net/5dsnucue/2/

//Toggle children on click.
function click(d) {
   // show is true if children currently hidden
   var show = !d.children; 
   showKids (show, d); // set the visibility of this node's kids

    // if on second level node and we want to show children of children
    // (don't need to same for hide, hiding intermediate node will do the job)
   if (d.depth === 1 && show) {
        var arr = d.children || d._children;
      // loop through kids and set them to visible
      arr.forEach (function(child) {
        showKids (true, child);
      })
   }
   update(d);
}

// showKids replaces simple toggle with a show parameter
function showKids (show, d) {
  if (!show) {
         d._children = d.children;
          d.children = null;
      } else {
          d.children = d._children;
          // blank this line as calling showKids with show=true
          // twice in a row will end up nulling .children and ._children
          // so keep d._children populated.
          //
          // Same doesn't apply to the 'if' condition above as we don't
          // pursue hiding down the tree.
          //d._children = null; 
     }
}

这使您可以执行以下操作:

  1. 点击第二级节点,显示第三和第四级节点
  2. 再次点击第二级节点,隐藏第三和第四级节点
  3. 再次单击第二级节点,显示第3和第4级节点
  4. 点击第3级节点,隐藏第4级节点
  5. 点击第二级节点,隐藏第三级节点
  6. 再次单击第二级节点,显示第3和第4级节点
  7. 上面的代码可能看起来比它需要的要复杂得多,但是通过简单的切换步骤6将返回到步骤4的状态 - 即仅显示第3级。代码中的逻辑确保在扩展第二级节点时始终显示第4级节点,而不管它们之前的状态如何。