问题描述
$(preview-button).click(...)
$(preview-button).slide(...)
$(preview-button).whatever(...)
这样做是否更好:
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 每次使用它时都需要找到该类的元素,但如果它存储在变量中,它会使用唯一标识符在变量中.无需查找.
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.
如果你只在一个地方使用选择器,你也可以做 chaining,这意味着你用相同的点符号一个接一个地添加一个方法:
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 中引用选择器是否比实际调用选择器更快?如果是这样,它有多大的不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!