简体   繁体   中英

jQuery show() vs adding Class

Which of these is more efficient (ie faster):

$(elem).show();

or

$(elem).addClass(displayClass); // Where display class is "display: block;"

Or are they identical?

It depends what you're after, they do different things:

  • $(elem).show(); - shows the element, restoring the display from before .hide() or restoring the default display for the element type
  • $(elem).addClass(displayClass); - adds a class, always with a certain display , not really restoring what was there - this is less flexible

Which is faster ? .addClass() hands down, you can test it yourself here , it simply does a lot less work than .show() does . However, it doesn't do as much feature-wise, so it's less flexible for the reasons above.

No, they are absolutely not identical.

There's a big difference between direct modifications to element styles and "indirect" modifications by changing the element's class, and that really should be pretty obvious. By writing cooperative code between Javascript and CSS, the class changes give you a lot more flexibility. The Javascript manages the state of elements, while the CSS drives the actual effect of that state.

The show() and hide() methods are handy and easy, but (in my opinion) managing state/appearance by class name is really a much more powerful and maintainable way to do things. In fact you can always write your own little jQuery plugins to add/remove classes that are meaningful to your app, to avoid having the class names themselves propagate through your code.

They're not identical; they work completely differently. They may in your case have the same effect, but don't count on it.

For example, addClass may not actually make the element visible in all cases. If the element has other styles which supercede the class (eg ID-level CSS, or inline styles, etc), then adding a class won't have any effect at all.

Also, setting display:block is only correct for elements that you want to be displayed as a block. If you've got inline elements (or worse, tables) and you try to display them as block, the results will probably not be what you're expecting.

Finally, .addClass() definitely involves more processing for the browser than .show() , so you're not making things any easier for your site by using it.

In short, if that's all you're trying to achieve, use .show() - it's the correct jQuery way to do it.

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