我正在使用树形布局来绘制图形。双击图中的子节点(最初从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);
}
答案 0 :(得分: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);
}
你看到孩子替换旧根的原因是因为你做了:
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);
}