Should hasClass precede removeClass - jQuery

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

提交回复
热议问题