简体   繁体   English

在jQuery中缓存$(this)是最佳实践吗?

[英]Caching $(this) in jQuery is a best practice?

We all know it's good to cache calls to the DOM, so instead of calling $('#someElement') more times, just save it to a var $someElement and use that. 我们都知道缓存对DOM的调用是很好的,因此与其多次调用$('#someElement'),不如将其保存到var $ someElement中并使用它。

But is it the same when using $(this) inside an event listener for example? 但是,例如在事件侦听器中使用$(this)时是否相同? Should $(this) be cached? 应该缓存$(this)吗?

Thank you. 谢谢。

如果多次调用$(this) ,最好执行var $this = $(this);

每次调用$(this)$(selector)都是一个函数调用,以创建一个新的jQuery对象...因此,如果您已经创建了一次,则缓存将保存调用该函数以再次创建同一对象的时间。

If you refer to the same element later in the event function, yes. 如果稍后在事件函数中引用相同的元素,则可以。 Outside of the function it doesn't make any sense to do so because the value of this will have changed. 功能之外它没有任何意义这样做,因为价值this将有改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM