Should hasClass precede removeClass - jQuery

后端 未结 3 441
旧时难觅i
旧时难觅i 2020-12-16 09:57

Is it necessary to check if a class exists before I use the removeClass api on an jquery object? eg.

if($(this).hasClass(\"test\"))
   $(this).r         


        
相关标签:
3条回答
  • 2020-12-16 10:12

    At least for Chrome, it is useful to add a hasClass() check before removeClass(), because jQuery unconditionally assigns elem.className to the new string even if the string hasn't changed, which causes Chrome to invalidate and recalculate the layout.

    One could argue that this is a bug in Chrome and it should check whether the className has actually changed from the previous value. However, it could also be that the browser has to recalculate the layout due to some obscure requirements that are written somewhere deep in the html spec.

    I haven't tested Firefox. The Safari web inspector is useless as it won't tell you why the layout was invalidated/recalculated (which javascript function caused it).

    0 讨论(0)
  • 2020-12-16 10:17

    Use just this:

    $(this).removeClass("test");
    

    There is no need to check for class existence.

    From jQuery sources we can see that removeClass method uses replace method to remove the substring:

    className = (" " + elem.className + " ").replace(rclass, " ");
    for (c = 0, cl = classNames.length; c < cl; c++) {
        className = className.replace(" " + classNames[c] + " ", " ");
    }​
    

    And replace won't remove anything if the matching substring does not exist.

    0 讨论(0)
  • 2020-12-16 10:17

    No, not necessary to check for removeClass().

    Just use

       $(this).removeClass("test");
    
    0 讨论(0)
提交回复
热议问题