本文介绍了如果多次使用$(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中缓存它?
发布评论