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屋!