【问题标题】:Draw graph for child nodes on click of the node of tree pattern in d3.js在 d3.js 中单击树模式的节点时为子节点绘制图形
【发布时间】:2016-06-04 06:59:07
【问题描述】:

我正在使用树形布局来绘制图表。双击图中的子节点(最初从 json 对象加载),它将使用示例项目中的 jsonChild 对象(子节点的 json 数据通常我们将使用来自 db 的 ajax 调用) 以树格式绘制图形。我面临的问题是,我从 json 对象中丢失了图形。我只为 jsonChild 对象重新绘制图形。我创建了一个sample jsfiddle project。我是 d3.js 的新手,请帮帮我。

  var node = svg.selectAll("g.node")
    .data(nodes, function(d){ 
        return d.id || (d.id = ++i); 
    });

// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", function(d){ return "translate(" + source.y0 + "," + source.x0 + ")"; })
    .on("click", click)
    .on("dblclick", getprofile);

nodeEnter.append("circle")
    .attr("r", 0)
    .style("fill", function(d){ 
        return d._children ? "lightsteelblue" : "white"; 
    }); 
function getprofile(){
    root = jsonChild;
    root.x0 = height / 2;
    root.y0 = 0;
     root.children.forEach(collapse);
    function collapse(d){
         if (d.children){
            d._children = d.children;
            d._children.forEach(collapse);
            d.children = null;
         }             
    }               
    update(root);
}

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    您的代码:

    function getprofile(){
        root = jsonChild;
        root.x0 = height / 2;
        root.y0 = 0;
         root.children.forEach(collapse);
        function collapse(d){
             if (d.children){
                d._children = d.children;
                d._children.forEach(collapse);
                d.children = null;
             }             
        }               
        update(root);
    }
    

    您看到 child 替换旧根的原因是因为您这样做:

    root = jsonChild;
    

    正确的代码应该是这样的:

    function getprofile(d) {
        //here d is node which you have double clicked.
        //to that node add the children array.This array can be fetched from Ajax as you were mentioning you want to do.
        d.children = jsonChild.children; 
    
        update(root);
    }
    

    【讨论】:

    • 它工作正常,再次感谢 Cyril 帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2014-01-17
    相关资源
    最近更新 更多