问题描述
我的ID为#wrapper
的div且所有元素都在其中.我正在通过
I have div with id #wrapper
and all element are inside it.I'm caching wrapper by doing
var $wrapper = $('#wrapper');
现在任何时候我想要做一个选择器或引用一个元素
Now any time i want to make a selector or reference an element, i do
$wrapper.find('#whatever').click(....
通过这样做,我避免再次用jQuery对象包装,因此我将来所做的任何选择器都将基于缓存的$wrapper
.但是另一方面,当我将find()
与缓存的$ wrapper一起使用时,我知道它将搜索#wrapper
内部的所有元素.我的问题是哪个更好,将缓存变量与find一起使用,然后发出click事件,或者干脆$('#whatever').click(..
By doing this i avoid wrapping with jQuery object again, so any selector i do in the future will be based on the cached $wrapper
. But on the other when i use find()
with the cached $wrapper, i know it will search all elements inside #wrapper
. My questions is whic is better better, use cached variable along with find then issue click event, or just simply do $('#whatever').click(..
whatever
可以是类或ID.
推荐答案
如果在whateverID
是ID
的情况下使用它,则$('#whateverID').click(..
会为您提供更好的性能,但是如果whateverCLASS
是类或其他任何东西除了ID
之外,$wrapper.find('whateverCLASS').click(....
会更好,因为遍历将被限制在特定容器中,该特定容器是整个DOM的子集
if you use it where whateverID
is an ID
then $('#whateverID').click(..
would give you slightly better performance, however if whateverCLASS
is class or anything other than ID
, $wrapper.find('whateverCLASS').click(....
will be better since the traversing will be limited to specific container which is subset of the whole DOM
这篇关于jQuery缓存选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!