jQuery源码解读之removeClass()方法分析

2020-05-22 17:11:43易采站长站整理

本文较为详细的分析了jQuery源码解读之removeClass()方法。分享给大家供大家参考。具体分析如下:

removeClass()方法和addClass()差别不大。这就来看看:
jQuery.fn.extend({
    removeClass: function( value ) {
        var classes, elem, cur, clazz, j, finalValue,
            i = 0,
            len = this.length,
            proceed = arguments.length === 0 || typeof value === “string” && value;
        if ( jQuery.isFunction( value ) ) {
            return this.each(function( j ) {
//这里就是根据你传递的移除类名的函数返回的类名,再次调用removeClass自身了。
                jQuery( this ).removeClass( value.call( this, j, this.className ) );
            });
        }
        if ( proceed ) {
            classes = ( value || “” ).match( rnotwhite ) || [];
            for ( ; i < len; i++ ) {
                elem = this[ i ];
                cur = elem.nodeType === 1 && ( elem.className ?
                    ( ” ” + elem.className + ” ” ).replace( rclass, ” ” ) :
                    “”
                );
                if ( cur ) {
                    j = 0;
                    while ( (clazz = classes[j++]) ) {
//区别在下面的while循环,当检索到当前DOM元素包含你要移除的类名,会用replace替换成” “
                        while ( cur.indexOf( ” ” + clazz + ” ” ) >= 0 ) {