问题描述
是否有人在DOM api中处理等效内容?
Is anybody working on a jQuery.closest() equivalent in the DOM api?
看似添加 matches()
相当于,因此本机最接近应该更容易编写。是否已向选择器添加 nearest()
?
Looks like the Selectors Level 2 draft adds matches()
equivalent to jQuery.is(), so native closest should be much easier to write. Has adding closest()
to Selectors come up?
推荐答案
使用Element实现此类功能。 matches()在性能方面似乎不是最优的,因为看起来match()会在每次测试父级时调用querySelectorAll(),而只有一次调用就足够了。
Implementing such function with Element.matches() seems not optimal in terms of performance, cause apparently matches() will make a call to querySelectorAll() every time you test a parent, while only one call is sufficient for the job.
这是MDN上最近()的polyfill。请注意一次调用querySelectorAll()
Here's a polyfill for closest() on MDN. Note a single call to querySelectorAll()
if (window.Element && !Element.prototype.closest) {
Element.prototype.closest =
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i,
el = this;
do {
i = matches.length;
while (--i >= 0 && matches.item(i) !== el) {};
} while ((i < 0) && (el = el.parentElement));
return el;
};
}
但请记住,像这样实现的函数在单独连接的树上无法正常工作(与document.documentElement root分离)
But bear in mind that function implemented like this will not work properly on unattached tree (detached from document.documentElement root)
//Element.prototype.closestTest = function(s){...as seen above...};
var detachedRoot = document.createElement("footer");
var child = detachedRoot.appendChild(document.createElement("div"));
detachedRoot.parentElement; //null
child.closestTest("footer"); //null
document.documentElement.append(detachedRoot);
child.closestTest("footer"); //<footer>
虽然在Firefox 51.0.1中实现的nearest()似乎可以在分离树上正常工作
Though closest() that is implemented in Firefox 51.0.1 seems to work fine with detached tree
document.documentElement.removeChild(detachedRoot);
child.closestTest("footer"); //null
child.closest("footer"); //<footer>
这篇关于使用原生DOM的最近祖先匹配选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!