jQuery 对象:缓存还是不缓存?

编程入门 行业动态 更新时间:2024-10-05 15:34:05
本文介绍了jQuery 对象:缓存还是不缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的 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 对象:缓存还是不缓存?

本文发布于:2023-11-26 18:55:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634781.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   对象   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!