我是 D3.js 的新手。我正在尝试从树布局中删除一个节点,但我找不到这样做的方法。这是一个示例树布局。
https://dl.dropbox.com/u/7098/tree/dynamic3.html
我想像这样动态删除:
https ://dl.dropbox.com/u/7098/tree/aaa.gif
我相信我应该对根 json 对象进行一些操作......
如果你们有想法,请告诉我。
我是 D3.js 的新手。我正在尝试从树布局中删除一个节点,但我找不到这样做的方法。这是一个示例树布局。
https://dl.dropbox.com/u/7098/tree/dynamic3.html
我想像这样动态删除:
https ://dl.dropbox.com/u/7098/tree/aaa.gif
我相信我应该对根 json 对象进行一些操作......
如果你们有想法,请告诉我。
this makes explicit seb's answer. where you set up your click handler, put this:
.on("click", function(d) {
if (d.parent && d.parent.children){
console.log('removing ' + d.name);
var nodeToDelete = _.where(d.parent.children, {name: d.name});
if (nodeToDelete){
d.parent.children = _.without(d.parent.children, nodeToDelete[0]);
}
}
});
that should get you what you want. make sure to call whatever method draws the tree from the source data, which is now modified. note: i'm using the underscore library to make use of _.where and _.without, although you could do this with pure js or with another library. some of the checks are for convenience and to prevent deletion of the root node, for example.
p.s. since you'll probably want to keep your expand/collapse behavior, then just put a conditional in the click callback to check for a modifier key to specify node deletion with, such as d3.event.altKey.
您需要遵循的原则在 d3.js 中折叠/展开树的子节点?. 该示例显示了如何在节点的单击处理程序上折叠树。
如果您修改已传递给布局管理器的数据结构,则树将相应更新。在上面示例中折叠树布局的情况下,您删除了节点的children
属性: 的值children
被存储在变量中_children
,因此可以再次切换回子节点。详见toggle
功能。
要删除节点,请遵循相同的逻辑,但从其父级列表中删除接收点击事件的节点children
。要查找父级,您可以在单击处理程序中遍历树,或者在数据结构中存储对每个父级的引用。