d3 缩进树用 child 关闭其他节点并仅打开特定节点

d3 indented tree close other nodes with child and open only specific node

你好,我将使用这个 jsfiddle 作为参考 http://jsfiddle.net/Ge58Q/16/

 function expandSingle(d) {
  if (d._children) {
    d.children = d._children;
    d._children = null;
 }
}

如您所见,我有一棵有多个分支的树。我想要做的是加载我只希望 NODE LIGHTNING 有打开的 child,那就是 NODE TURBO。 NODES CUTE AND NODE TOXIC 我希望隐藏它们的 child。是否可以只打开我想要的特定节点????????

我觉得跟上面的代码有点关系

如果你想扩展从根到具有特定名称的节点的路径,你可以使用一些算法来获取路径,例如深度优先,带有存储路径的堆栈。这是封装递归函数的函数示例,returns 数组的索引为从根到节点的 children 个位置:

function getPathToNode(val, rootNode) {
    var stack = [];
    var nodeFound = false;
    function getPathRec(node) {
        if (nodeFound) {
            return;
        }
        if (node._children || node.children) {
            var nodeChildren = node.children ? node.children : node._children;
            for (var i=0; i<nodeChildren.length; i++) {
                if (!nodeFound) {
                    stack.push(i);
                    getPathRec(nodeChildren[i]);
                }
            }
        }
        if  (node.name == val && !nodeFound) {
            nodeFound = true;
            return;
        } else if (!nodeFound) {
            stack.pop();
        }
    }
    getPathRec(rootNode);
    return stack;
}

那么你可以展开路径上的节点:

function expandToNode(val) {
    path = getPathToNode(val, flare);
    currentNode = flare;
    for (var i=0; i<path.length - 1; i++) {
        currentNode = currentNode.children[path[i]];
        expandSingle(currentNode);
    }
}

所以只需调用函数 expandToNodes(val) 并将节点名称设为 val parameter:

expandToNode('turbo');

这是有效的 JSFiddle:http://jsfiddle.net/Ge58Q/18/

限制:如果有多个同名的节点,它只展开第一个找到的节点。如果你想展开所有的路由,你可以遍历整个根和return所有的路径。我仅使用您的树数据测试了代码,因此可能存在一些错误。