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

编程入门 行业动态 更新时间:2024-10-05 13:23:59
本文介绍了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:56:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634782.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   对象   jQuery

发布评论

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

>www.elefans.com

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