简体   繁体   中英

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? 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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