D3.js Tree Expand All and Collapse All

前端 未结 3 2313
再見小時候
再見小時候 2021-02-20 07:15

I\'m building a Tree using D3.js and what I am trying to do is add two buttons, Expand All and Collapse All to the top of the page like this.

3条回答
  •  梦如初夏
    2021-02-20 07:49

    Try this code. Here is the working JsFiddle.

    function expand(d){   
        var children = (d.children)?d.children:d._children;
        if (d._children) {        
            d.children = d._children;
            d._children = null;       
        }
        if(children)
          children.forEach(expand);
    }
    
    function expandAll(){
        expand(root); 
        update(root);
    }
    
    function collapseAll(){
        root.children.forEach(collapse);
        collapse(root);
        update(root);
    }
    

提交回复
热议问题