d3.js tree diagram - expand only next level nodes when clicking on root node

末鹿安然 提交于 2019-12-10 11:46:41

问题


I have a tree diagram I'm trying to adapt here, but the problem is that it automatically expands all root nodes in the tree when I click on a collapsed node, rather than just expanding the immediate children. Here's a fiddle. How do I resolve this?

http://jsfiddle.net/heaversm/nw577/

The function for handling the toggling / collapsing of the nodes:

function toggleChildren(d) {
    if (d.children) {
        d._children = d.children;
        d.children = null;
    } else if (d._children) {
        d.children = d._children;
        d._children = null;
    }
    return d;
}

回答1:


The problem is that all nodes start expanded and only the state of an individual node is toggled on click. That is, all nodes underneath the root are still expanded, but not shown. As soon as you click the root node, they are. So they are not expanded as well as the root, but they were never collapsed.

To fix, just collapse all nodes to start with:

tree.nodes(root).forEach(function(n) { toggle(n); });

Complete demo here.



来源:https://stackoverflow.com/questions/23940331/d3-js-tree-diagram-expand-only-next-level-nodes-when-clicking-on-root-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!