jQuery对象:缓存还是不缓存? [英] jQuery object: to cache or not to cache?
问题描述
我的Javascript(JS)代码给我带来了一些麻烦,因为有时我需要在同一函数中多次访问同一DOM元素. 此处
I have some trouble that comes from my Javascript (JS) codes, since I sometimes need to access the same DOM elements more than once in the same function. Some reasoning is also provided here.
从性能的角度来看,一次创建一个jQuery对象然后对其进行缓存是更好的方法,还是随心所欲地创建相同的jQuery对象呢? 示例:
From the point of view of the performance, is it better to create a jQuery object once and then cache it or is it better to create the same jQuery object at will? Example:
function(){
$('selector XXX').doSomething(); //first call
$('selector XXX').doSomething(); //second call
...
$('selector XXX').doSomething(); // n-th call
}
或
function(){
var obj = $('selector XXX');
obj.doSomething(); //first call
obj.doSomething(); //second call
...
obj.doSomething(); // n-th call
}
我认为答案可能取决于"n"的值,因此假设n是一个小"数字(例如3),然后是一个中等数字(例如10),最后是一个大数字(例如30,就像该对象用于for循环中的比较一样.
I suppose that the answer probably depends by the value of "n", so assume that n is a "small" number (e.g. 3), then a medium number (e.g. 10) and finally a large one (e.g. 30, like if the object is used for comparison in a for cycle).
谢谢.
推荐答案
最好缓存元素,如果n大于1,则缓存元素,或将操作链接在一起(您可以对大多数 jQuery操作执行$('#something').something().somethingelse();
,因为它们通常会返回包装后的集合本身).顺便说一句,以货币符号$
开头的高速缓存变量的命名已经成为一种标准,因此在代码的后期,很明显,您正在对jQuery集执行操作.因此,您会看到很多人先执行var $content = $('#content');
然后执行$content.find('...');
.
It is always better to cache the element, if n is greater than 1, cache the element, or chain the operations together (you can do $('#something').something().somethingelse();
for most jQuery operations, since they usually return the wrapped set itself). As an aside, it has become a bit of a standard to name cache variables beginning with a money sign $
so that later in the code it is evident that you are performing an operation on a jQuery set. So you will see a lot of people do var $content = $('#content');
then $content.find('...');
later on.
这篇关于jQuery对象:缓存还是不缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!