[英]Jquery - Should I not repeat selectors (store in a variable)?
There are some times when I find myself repeating a selector several times. 有时我发现自己多次重复选择器。 Should I be somehow storing a jquery object to a variable and then just using that one?
我应该以某种方式将jquery对象存储到变量然后只使用那个? As a quick example, what about the following?:
作为一个简单的例子,以下是什么?:
$('a.contactus').css('padding', '10px');
$('a.contactus').css('margin', '4px');
$('a.contactus').css('display', 'block');
Now I know this isn't a great example, since effectively you could just chain each css function. 现在我知道这不是一个很好的例子,因为有效地你可以链接每个css函数。 But suppose in between each of those was a conditional statement or something to stop you from chaining.
但是假设每一个都是条件性陈述或某些东西阻止你链接。
Can I store a jquery object in a variable? 我可以在变量中存储jquery对象吗? And if so, when should I / can I?
如果是这样,我什么时候可以?
When reusing it more than once (and you can't chain) storing it in a variable isn't a bad idea, the more often it's used or the more expensive the selector, the better idea storing it as a variable becomes. 当重复使用它(并且你不能链)将它存储在一个变量中并不是一个坏主意,它使用的频率越高或选择器越昂贵,将它作为变量存储就越好。 For example the performance of
$(this)
a few times is trivial, but the performance of $("[attr=val]")
is very poor and should absolutely be cached if reused. 例如,
$(this)
几次的性能是微不足道的,但$("[attr=val]")
的性能非常差,如果重复使用,应该绝对缓存。 If in doubt, cache it as a variable. 如果有疑问,请将其缓存为变量。
Just another tip, in that example you can also pass an object to .css()
: 只是另一个提示,在该示例中,您还可以将对象传递给
.css()
:
$('a.contactus').css({ padding: '10px', margin: '4px', display: 'block' });
Should I be somehow storing a jquery object to a variable and then just using that one?
我应该以某种方式将jquery对象存储到变量然后只使用那个?
You should for the sake of performance when possible. 你应该尽可能为了表现 。 You can for example re-write your code like this:
例如,您可以像这样重写代码:
var $el = $('a.contactus');
$el.css('padding', '10px');
$el.css('margin', '4px');
$el.css('display', 'block');
You can make it even shorter like this: 你可以把它缩短得更短:
$el.css({
padding: '10px',
margin:'4px',
display: 'block'
});
Storing common/repetitive selector in a variable is also useful when writing jquery plugins to store the $(this)
in a variable. 在编写jquery插件以将
$(this)
存储在变量中时,将常用/重复选择器存储在变量中也很有用。
You can do this 你可以这样做
var myvar = $('a.contactus');
myvar.css('padding', '10px').css('margin', '4px').css('display', 'block');
but for readability i do this 但为了便于阅读,我这样做了
var myvar = $('a.contactus');
myvar.css('padding', '10px')
.css('margin', '4px')
.css('display', 'block');
basically every time you use $(someselector) you iterate through the dom. 基本上每次使用$(someselector)时,你都会遍历dom。 If you can you should store the element reference.
如果可以,您应该存储元素引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.