jQuery $(this)是否需要缓存 [英] Does jQuery $(this) need to be cached

查看:83
本文介绍了jQuery $(this)是否需要缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一些有关jQuery性能的博客文章(即

I recently came accross some blog posts about jQuery performance (i.e. http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/) and it was stated in all of them that we should cache the jQuery objects to javascript variables.

我需要知道的是,这是否也适用于$(this). 如果这样做,我会提高性能吗?

What I need to know, though, is if this applies to $(this) as well. Am I going to gain in performance if I do this:

$("#some-link").click("click", function(){
  var $this = $(this);
  $this.doSomeThing();
});

预先感谢您的帮助.

推荐答案

this可能引用了许多不同的对象.

this may refer to many different objects.

缓存$(this)可能并不重要,因为this已经是当前元素,因此jQuery无需在DOM中搜索该元素.

Caching $(this) may not be important, because this is already the current element and thus jQuery does not need to search the DOM for this element.

但是在单个函数中,如果多次调用$(this),明智的做法是将$(this)放在变量中,而不是多次调用$(this).

However in a single function if you have more than one times calling $(this), it is wise to put $(this) to a variable instead of calling $(this) many times.

$("#some-link").click("click", function(){
  var $this = $(this);
  $this.doSomeThing();
  $this.doThisThing();
  $this.doThatThing();
});

会比

$("#some-link").click("click", function(){
  $(this).doSomeThing();
  $(this).doThisThing();
  $(this).doThatThing();
});

这篇关于jQuery $(this)是否需要缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆