【发布时间】:2013-07-01 04:42:47
【问题描述】:
我有一个 D3.js collapsible tree,它有一堆节点。树中有几条路径,其中存在只有一个子节点的节点序列。想象一下这棵树:
5
/
1 - 2 - 3 - 4 -6
\
7
当1节点被点击时,我希望它变成:
5
/
1 - 4 -6
\
7
现在我的代码正常展开和折叠节点。如何选择那些 intermediate 节点,以便像现在一样使用切换功能定位它们?
我的代码与示例中的基本相同,除了我添加的一些与此问题无关的内容。 toggle() 函数接收一个指向node 的指针,并使可见的子节点(在children 数组中)不可见(通过将它们移动到_children 数组中)。这会将 所有 孩子(以及孙子、曾孙...)打到该特定节点,但我需要它在找到具有 exactly 1 的节点时继续孩子,那么,如果它找到一个没有孩子的节点,我希望它是可见的;如果节点有超过 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;
}
}
}
【问题讨论】:
标签: javascript arrays d3.js