[英]Jquery's closest() slow's my app down when it doesn't find an element, how do I do the same query but faster?
I want to see if a element is sat inside another one, I do this a lot of times in my app like this: 我想看看一个元素是否位于另一个元素中,我在我的应用程序中这样做了很多次:
is_inside_something: function(element){
return element.closest(".something").length == 1
}
So I'm see if there's an parent called is returned for ".something" 所以我看看是否有一个叫做“.something”的父母被叫回来
The problem I've noticed webpages slowing down and when I take a look at the webkit profiler it's this bit of code that's doing it. 这个问题我注意到网页速度变慢了,当我看一下webkit分析器时,就是这样做的代码。
Is there a quicker way of saying: 有没有更快的方式说:
"Does the class '.something" exist as a parent of this element at all?"
It seems that this is taking up so much memory because it goes up through the while dom of the page all the way up to the head every time it's called. 这似乎占用了大量的内存,因为它每次调用时都会在页面的dom上升到头部。 Which is a lot in my case.
在我的案例中,这很多。
Try to use pure javascript and limit the number of DOM climb-up iterations: 尝试使用纯javascript并限制DOM爬升迭代次数:
var ctr=0;
var is_in_something=function(element,steps){
if(ctr<steps){
if($(element.parentNode).hasClass(".something")){
return true;
}else{
ctr++;
return is_in_something(element.parentNode,steps);
}
}else{
return false;
}
}
is_in_something(document.getElementById("mydiv"),20);
The above code will try to check the 20 parents of "mydiv". 上面的代码将尝试检查“mydiv”的20个父母。 It will return true if one of the parent has the class ".something".
如果其中一个父类具有类“.something”,它将返回true。 If after 20 iterations no such parent is found, then it will return false.
如果在20次迭代后没有找到这样的父级,那么它将返回false。
So, with this you can control the number of levels you want to climb-up the DOM and not having to reach the HEAD everytime. 因此,通过这种方式,您可以控制想要爬上DOM的级别数,而不必每次都能到达HEAD。
There is also the "parents" function depending on your context I think it helps. 还有“父母”功能取决于您认为有帮助的背景。 Here is a performance test
这是一个性能测试
http://jsperf.com/jquery-parents-vs-closest/2 http://jsperf.com/jquery-parents-vs-closest/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.