在jQuery中引用选择器是否比实际调用选择器更快?如果是这样,有什么不同? [英] Is referencing a selector faster in jquery than actually calling the selector? if so, how much does it make a difference?

查看:51
本文介绍了在jQuery中引用选择器是否比实际调用选择器更快?如果是这样,有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(preview-button).click(...)
$(preview-button).slide(...)
$(preview-button).whatever(...)

这样做是更好的做法吗?

Is it a better practice to do this:

var preview-button = $(preview-button);
preview-button.click(...);
preview-button.click(...);
preview-button).slide(...);
preview-button.whatever(...);

这样做可能是更好的做法,以保持代码的干净和模块化,但是在性能方面是否有所作为?一个过程比另一个过程需要更长的时间吗?谢谢大家.

It probably would be better practice to do this for the sake of keeping code clean and modular, BUT does it make a difference performance wise? Does one take longer to process than the other? Thanks guys.

推荐答案

是的,当您使用选择器而不将其存储在变量中时,jQuery需要每次都解析DOM.

Yes it does, when you use the selector without storing it in a variable jQuery needs to parse the DOM EVERY TIME.

如果您有类似$(".class")之类的内容,那么每次使用jQuery时,jQuery都需要查找该类的元素,但是如果将其存储在变量中,它将使用该变量中的唯一标识符.无需查找.

If you had something like $(".class") jQuery would need to find the elements with that class every time you use it but if it is stored in a variable it uses the unique identifier in the variable. No need to lookup.

是的,我完全建议将其存储到变量中.

So yeah i would totally recommend storing it into a variable.

更新: 添加了链接作为替代.

UPDATE: Added chaining as an alternative.

如果仅在一个位置使用选择器,则还可以进行链接,这意味着您可以使用相同的点符号依次添加一个方法,如下所示:

If you only use the selector in one place you can also do chaining which means you add one method after another with the same dot notation like this:

$(".class")
       .click(function(){ ... })
       .mouseenter(function(){ ... })
       .css( ... );

这篇关于在jQuery中引用选择器是否比实际调用选择器更快?如果是这样,有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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