如果多次使用$(this),是否应该在jQuery中缓存它?

编程入门 行业动态 更新时间:2024-10-24 23:15:17
本文介绍了如果多次使用$(this),是否应该在jQuery中缓存它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道,如果您多次使用选择器,则应该缓存该选择器的结果.一个例子是:

I know that you are supposed to cache the results of a selector if you use it more than once. An example would be:

var $selected = $('.some-selected-element'); process($selected); doStuff($selected);

但是如果多次使用$(this)缓存,对性能有什么好处?

But is there any performance benefit to caching $(this) if it is used multiple times?

$('.some-selector').hover(function () { if (!$(this).hasClass('some-other-class')) { $(this).addClass('another-class'); } process($(this)); }

推荐答案

是的,性能有所提高,因为它可以防止jQuery解释您的选择器.

Yes, there's a performance increase, because it prevents jQuery from having to interpret your selector.

这里是选择器的解释,以及您将忽略的内容. github/jquery/jquery/blob /master/src/core.js#L78-188

Here's the interpretation of a selector, and what you'll be bypassing. github/jquery/jquery/blob/master/src/core.js#L78-188

本质上,这部分

if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; }

更多推荐

如果多次使用$(this),是否应该在jQuery中缓存它?

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

发布评论

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

>www.elefans.com

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