jQuery Closest-它是如何工作的? [英] jQuery Closest - how does it work?
问题描述
jQuery的文档状态
对于集合中的每个元素,通过测试元素本身并在DOM树中遍历其祖先,获得与选择器匹配的第一个元素.
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
在我看来,这里的实用词是祖先.这意味着如果有人使用
The operational word here, to my eyes, is ancestor. Which would imply that if one uses
elem.closest(selector)
并且选择器不是elem的祖先,什么也找不到.但是,它所读取的同一文档中的位置略低
and selector is not an ancestor of elem nothing will be found. However, a little lower down in the same document it reads
向上移动DOM树,直到找到与提供的选择器匹配的对象
Travels up the DOM tree until it finds a match for the supplied selector
我将其解释为
,直到< body>标签来得到它的男人.请注意,此处没有提及 parent 或祖先.
我写了一个快速的小提琴,这似乎表明前一种说法是正确的.但是,我认为最好在这里发布,看看是否有人可以确认这一点.
I wrote up a quick fiddle which appears to suggest that it is the former statement that is correct. However, I thought it best to post here and see if anyone else can confirm this.
推荐答案
.closest()
的实现是这样的(用伪代码):
The implementation of .closest()
works like this (in pseudo code):
while (node) {
if (node matches selector) {
return node;
}
node := node.parentNode
}
换句话说,它仅通过跟随父链来遍历.
In other words, it traverses up by following the parent chain only.
这篇关于jQuery Closest-它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!