假设我有一个div
叫做 Z .
Z that is a sub-sub-sub... child of a
div called
B which is a child of a
div called
A`。
B
从到的所有块Z
都设置为display=none
(A
可见)。
如果我单击链接到 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)
}
}