jQuery show() vs adding Class

前端 未结 3 1616
小蘑菇
小蘑菇 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: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.

提交回复
热议问题