使用jQuery,像这样(以下是一种不使用jQuery除事件外的解决方案;如果重复函数调用很重要,则调用更少的函数):
使用jQuery,像这样(下面提供了一种不使用jQuery除事件外的解决方案;如果函数调用次数很重要,则可以调用较少的函数):
$(".rightArrow").click(function () {
const rightArrowParents = [];
$(this)
.parents()
.addBack()
.not("html")
.each(function () {
let entry = this.tagName.toLowerCase();
const className = this.className.trim();
if (className) {
entry += "." + className.replace(/ +/g, ".");
}
rightArrowParents.push(entry);
});
console.log(rightArrowParents.join(" "));
return false;
});
实时示例:
$(".rightArrow").click(function () {
const rightArrowParents = [];
$(this)
.parents()
.addBack()
.not("html")
.each(function () {
let entry = this.tagName.toLowerCase();
const className = this.className.trim();
if (className) {
entry += "." + className.replace(/ +/g, ".");
}
rightArrowParents.push(entry);
});
console.log(rightArrowParents.join(" "));
return false;
});
<div class=" lol multi ">
<a href="#" class="rightArrow" title="Next image">Click here</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
(在实时例子中,我已经更新了 div
上的 class
属性为 lol multi
, 以演示处理多个类的方法。)
代码使用 parents
获取被点击元素的祖先元素,通过 not
移除其中的 html
元素(因为你从 body
开始),然后循环创建每个父级元素的条目,并将其推入数组。接着使用 addBack
将 a
添加回集合中,这也改变了集合的顺序到你所需的顺序(parents
得到的是你想要的父级元素的反向顺序,但是 addBack
可以让它按 DOM 的正常顺序排列)。最后使用 Array#join
创建以空格分隔的字符串。
在创建条目时,我们会修剪 className
(因为在 class
属性中前导和尾随空格保留,但没有意义),然后如果还有剩余内容,就使用点号(.
)将一个或多个空格的系列替换为点号,以支持具有多个类的元素(例如 <p class='foo bar'>
的 className
为 "foo bar"
,所以该条目最终是 p.foo.bar
)。
只是为了完整性起见,这是 jQuery 可能过于繁琐的情况之一,你可以直接遍历 DOM 树来实现这个效果:
$(".rightArrow").click(function () {
const rightArrowParents = [];
for (let elm = this; elm; elm = elm.parentNode) {
let entry = elm.tagName.toLowerCase();
if (entry === "html") {
break;
}
const className = elm.className.trim();
if (className) {
entry += "." + className.replace(/ +/g, ".");
}
rightArrowParents.push(entry);
}
rightArrowParents.reverse();
console.log(rightArrowParents.join(" "));
return false;
});
实时示例:
$(".rightArrow").click(function () {
const rightArrowParents = [];
for (let elm = this; elm; elm = elm.parentNode) {
let entry = elm.tagName.toLowerCase();
if (entry === "html") {
break;
}
const className = elm.className.trim();
if (className) {
entry += "." + className.replace(/ +/g, ".");
}
rightArrowParents.push(entry);
}
rightArrowParents.reverse();
console.log(rightArrowParents.join(" "));
return false;
});
<div class=" lol multi ">
<a href="#" class="rightArrow" title="Next image">Click here</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
在那里,我们只需使用标准的parentNode
属性(或者我们可以使用parentElement
)来反复向上遍历树,直到我们没有父级或者看到html
元素。然后,我们将数组反转(因为它与您想要的输出是相反的),并加入它,就可以了。