gpt4 book ai didi

javascript - 在 D3 Js Vertical Tree 中单击一次在父级下打开所有子级

转载 作者:行者123 更新时间:2023-11-30 20:10:59 29 4
gpt4 key购买 nike

当我点击父级时,我试图打开父级下的所有子级

单击第 3 个父级后,它应该立即打开所有左右子级,如果当我单击父级时所有子级都处于打开状态,它应该全部关闭。为了左右移动,我在嵌套的 JSON 中把所有的 child 都放在另一个下面,这样我就可以左右移动了下面是代码,我在 d3js 垂直树中使用

if (d.children) {
_callerNode = null;
_callerMode = 0; // Collapse
d._children = d.children;
d.children = null;
} else {
_callerNode = null;
_callerMode = 1; // Expand
if (d.parent.children && d.IC==="Yes") {
expand(d)
}
else{
d.children = d._children;
d._children = null;
}
}
update(d);
});
} else {
if (d.children) {
_callerNode = d;
_callerMode = 0; // Collapse
d._children = d.children;
d.children = null;
} else {
_callerNode = null;
_callerMode = 1; // Expand
if (d.parent.children && d.IC==="Yes") {
expand(d)
}
else {
d.children = d._children;
d._children = null;
}
}
update(d);
}

当我点击父级时它应该自动打开左右子级以后我可能还有机会为 parent 2 左右生更多的 child

任何帮助将不胜感激提前感谢所有帮助

最佳答案

您可以使用与启动图表时调用的 collapse 函数类似的原理,但该函数将展开所有节点。这是适当的 expand 函数(我已插入到 collapse 函数正下方的代码中):

        expand = function(d) {
if (d._children) {
d.children = d._children;
d.children.forEach(expand);
d._children = null;
}
},

然后您只需要在适当的时间调用它,即在您的 nodeclick 函数期间:

                if (d.children) {
_callerNode = d;
_callerMode = 0; // Collapse
d._children = d.children;
d.children = null;
} else {
_callerNode = null;
_callerMode = 1; // Expand
// INSERT HERE!
// if the node depth is 2 or more, call the `expand` function
if ( d.depth >= 2 ) {
expand(d)
}
// otherwise, just do the standard node expansion
else {
d.children = d._children;
d._children = null;
}
}

顺便说一句,你有两段非常相似的代码,彼此相隔几行:

                    if (d.children) {
_callerNode = null;
_callerMode = 0; // Collapse
d._children = d.children;
//d._children.forEach(collapse);
d.children = null;
} else {
_callerNode = null;
_callerMode = 1; // Expand
if ( d.depth >= 2 ) {
expand(d)
}
else {
d.children = d._children;
d._children = null;
}
}
update(d);
});
} else {
if (d.children) {
_callerNode = d;
_callerMode = 0; // Collapse
d._children = d.children;
d.children = null;
} else {
_callerNode = null;
_callerMode = 1; // Expand
if ( d.depth >= 2 ) {
expand(d)
}
else {
d.children = d._children;
d._children = null;
}
}
update(d);
}

你可以考虑重构这个,这样你就没有这个重复的代码 - 例如创建一个新函数:

function expandCollapse(d, caller) {
if (d.children) {
_callerNode = caller;
_callerMode = 0; // Collapse
d._children = d.children;
d.children = null;
} else {
_callerNode = null;
_callerMode = 1; // Expand
if ( d.depth >= 2 ) {
expand(d)
}
else {
d.children = d._children;
d._children = null;
}
}
update(d);
}

然后用 expandCollapse(d, null)expandCollapse(d, d) 替换现有代码。

关于javascript - 在 D3 Js Vertical Tree 中单击一次在父级下打开所有子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52418614/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com