简体   繁体   中英

Tree structure-starting with only root node onload

I am building a tree diagram as in: http://bl.ocks.org/2503502 .

I would like to have a tree with all the nodes collapsed, so the initial graph should contain only one node (the root). When the page loads, only the root node should be shown, then when clicked, the rest of the child nodes are shown.

How do I do this?

I can see this was asked a while ago but I'll answer it anyway as I was in a similar situation.

You have a couple of options here depending if you would like the root node clickable and for the child nodes to appear in full (after clicking on root) as it appears currently on the example you provided or if you want all of the child nodes to be collapsed aswell.

OPTION 1 (only root node collapsed)

On initialisation of the d3 object where in the function it is coded with update(root); (do a ctrl + f or cmd + f for it) put in toggle(root) . The variable name root is according to the example given, your version and function names may be different (as you have not provided an example code to work off).

OPTION 2 (all nodes collapsed)

You do the same as Option 1 above but just before the newly inserted toggle(root); you also put root.children.forEach(toggleAll); where toggleAll is a function you will also need to insert which is:

function toggleAll(d) {
    if (d.children) {
        d.children.forEach(toggleAll);
        toggle(d);
    }
}

Alternative Options

The options I have given are not limited to the above. If you follow this example ( https://stackoverflow.com/a/11649427 ) by brantolsen.github.com you will find other examples of implementing what you are trying to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM