我正在使用D3.js Tree Layout Version 3 with https://jsfiddle.net/CJ_Shijo/e7osumLp/ example。在jsfiddle示例中,我可以在单击子节点时隐藏不相关的父节点。我也可以在点击叶子节点的同时动态添加节点。下面两个函数用于将节点动态添加到叶节点。
function updateJson(node) {
var associatedItems = getNewData(node);
node._children = associatedItems;
// if the node has visible children, make them invisible
if (node.children) {
node._children = node.children;
node.all_children = node.children;
node.children = null;
}
// if the node has invisible children, make them visible
else {
node.children = node._children;
node.all_children = node._children;
node._children = null;
}
// update the view to reflect the new changes
if (node.children) {
node.children.forEach(function (n) {
n.hidden = false;
});
if (node.parent) {
node.parent.children = [node, ];
node.parent.hidden = true;
node.parent.children.filter(function (n) {
return n !== node;
}).forEach(function (n) {
n.hidden = true;
});
}
}
}
function getNewData(node) {
/* Return a list of things that will be added as children to the json. */
return [{
name: "E",
}, {
name: "F",
}, {
name: "G",
}
];
}我已经使用d3 V3版本实现了这一功能。我需要实现与d3 V4版本相同的功能。
我用这个jsfiddle https://jsfiddle.net/CJ_Shijo/km4txwna/示例启动了d3 v4版本。
我有像下面这样的扁平json数据。
var flatData = [
{"name": "Top Level", "parent": null},
{"name": "Level 2: A", "parent": "Top Level" },
{"name": "Level 2: B", "parent": "Top Level" },
{"name": "Son Of A", "parent": "Level 2: A" },
{"name": "Daughter Of A", "parent": "Level 2: A" }
];通过使用下面的d3方法,我创建了分层(树)数据。
var treeData = d3.stratify()
.id(function(d) { return d.name; })
.parentId(function(d) { return d.parent; })
(flatData);
treeData.each(function(d) { d.name = d.id; });
var root = d3.hierarchy(treeData, function(d) { return d.children; });在v4版本的示例中,我遇到了向叶节点动态添加节点的问题,nodes.Child节点连接不正确。有没有人可以帮我在V4版本上做同样的事情?
发布于 2017-09-18 17:32:08
下面的功能有助于在d3 v4中实现向叶子节点添加节点。
function addNodes(selectedNode) {
var data = [{"name":"First"},{"name":"Second"},{"name":"Third"}];
if (!selectedNode.children) {
var childArray = [];
}
selectedNode.height = selectedNode.height + 1;
data.forEach(function (d) {
var obj = d3.hierarchy(d);
obj.data.parent = selected.name;
obj.depth = selected.depth + 1;
obj.parent = selected;
obj.name = d.name;
childArray.push(obj);
});
selectedNode.children = childArray;
}https://stackoverflow.com/questions/46080747
复制相似问题