Should hasClass precede removeClass - jQuery

后端 未结 3 447
旧时难觅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).

提交回复
热议问题