我有一个 D3.js collapsible tree它有一堆节点。树中有几条路径,其中存在只有一个子节点的节点序列。想象一下这棵树:
5
/
1 - 2 - 3 - 4 -6
\
7
当点击1
节点时,我希望它变成:
5
/
1 - 4 -6
\
7
现在我的代码可以正常展开和折叠节点。如何选择这些中间节点,以便我可以像现在一样使用切换功能来定位它们?
我的代码与示例中的代码基本相同,除了我添加的一些与此问题无关的内容。 toggle()
函数接收指向 node
的指针,并使可见的子节点(在 children
数组中)不可见(通过将它们移动到它们是 _children
数组)。这会击中该特定节点的所有子代(以及孙子和曾孙,...),但我需要它在找到恰好 1的节点时继续child,那么,如果它找到一个没有子节点的节点,我希望它可见;如果该节点有超过 1 个子节点,我希望它从该点开始显示所有子节点。
这是在节点之一中调用 onclick 的 toggle()
函数代码:
function toggle(d) {
var myLength;
if(d.children){myLength = d.children.length;}
else{myLength=0;}
if (myLength === 1) {
//next will be the first node we find with more than one child
var next = d.children[0];
for (;;) {if(next.hasOwnProperty('children')){
if (next.children.length === 1) {
next = next.children[0];
} else if (next.children.length > 1) {
break;
}
} else {
// you'll have to handle nodes with no children
break;
}
}
d._children = d.children;
d.children = [next];
}else{
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
}
}
最佳答案
该切换函数不执行任何类型的逻辑检查,它只是删除和添加子项。为了做你想做的事,你需要使用一些逻辑和数据遍历,但这并非不可能。尝试这样的事情:
function toggle(d) {
if (d.children.length === 1) {
//next will be the first node we find with more than one child
var next = d.children[0];
for (;;) {
if (next.children.length === 1) {
next = next.children[0];
} else if (next.children.length > 1) {
break;
} else {
//you'll have to handle nodes with no children
}
}
d._children = d.children;
d.children = [next];
}
}
关于javascript - D3.js 可折叠树 - 展开/折叠中间节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17448894/