2

假设我有一个div叫做 Z .Z that is a sub-sub-sub... child of adiv calledB which is a child of adiv calledA`。

B从到的所有块Z都设置为display=noneA可见)。

如果我单击链接到 block 的锚点Z,我希望它显示出来。

为此,我需要设置块 Z 的显示block,还要设置其父级的 display* 到块,以及它的父级和一直到块 B....

我不想对所有可能的关卡进行“硬”编码,因为我可以有 2、4 或 10 个关卡。所以我想找到一种自动完成的方法。

我对上面的示例进行了一些简化,因为我必须设置display=block每 2 个“代”(cf 在我的代码中parentNode.parentNode

到目前为止,这是我的代码(兔子洞下有 2 级!)而不是自动化:

function indexLink(link_to_anchor) {
    var x = document.getElementById(link_to_anchor);
    if (x.parentNode.parentNode.getAttribute("class") == "divcodebox") {
        if (x.parentNode.parentNode.parentNode.parentNode.getAttribute("class") == "divcodebox") {
            x.parentNode.parentNode.parentNode.parentNode.style.display = "block";
        }
        x.parentNode.parentNode.style.display = "block";
    }
    x.style.display = "block";
}

递归使用 indexLink() :

function indexLink(link_to_anchor) {
    var x = document.getElementById(link_to_anchor);
    x.style.display = "block";
    if (x.parentNode.parentNode.getAttribute("class") == "divcodebox") {
        x.parentNode.parentNode.style.display = "block";
        indexLink(x)
    }
}
4

3 回答 3

2

一个简单的for循环怎么样?

    var x = document.getElementById(link_to_anchor);
    for (parent = x.parentNode; parent; parent = parent.parentNode) {
      // do whatever
    }

您当然可以保留一个计数器来检查您已经遍历了多少步等。.parentNode来自关卡的引用document将是null,这样就结束了迭代。(你也可以提前跳出循环。)

于 2019-05-08T14:01:13.840 回答
1

这只是为了展示您的递归函数应该如何基于您的代码而不是完成的示例。

;function indexLink(element){
    //REM: Change the parameter to the actual element instead of its id
    //var x = document.getElementById(link_to_anchor);

    //REM: Check if the element exists and the style does not equal block
    //REM: If the styles are set by class you need to change this to computed style
    if(element && element.style.display !== 'block'){
        //REM: Set the display to block
        element.style.display = 'block';

        //REM: Repeating the same logic for the parentNode
        indexLink(element.parentNode)
    }
};
于 2019-05-08T14:35:10.863 回答
0
function recursiveApply(from, to, fn) {
    let current = from;

    while(current !== to) {
        fn(current);
        current = current.parentElement;
    }
}

然后像这样使用它:

var a = document.getElementById("1");
var b = document.getElementById("2");

recursiveApply(a, b, function(element) {
    // do stuff with the element
    console.log(element)
});
于 2019-05-08T14:04:33.273 回答