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? 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 effectiv开发者_如何学运维ely you could just chain each css function. 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? 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. If in doubt, cache it as a variable.
Just another tip, in that example you can also pass an object to .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?
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.
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. If you can you should store the element reference.
精彩评论