jQuery show() vs adding Class

前端 未结 3 1593
小蘑菇
小蘑菇 2020-12-17 19:38

Which of these is more efficient (i.e. faster):

$(elem).show();

or

$(elem).addClass(displayClass); // Where display class i         


        
相关标签:
3条回答
  • 2020-12-17 20:09

    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.

    0 讨论(0)
  • 2020-12-17 20:09

    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.

    0 讨论(0)
  • 2020-12-17 20:12

    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.

    0 讨论(0)
提交回复
热议问题