码迷,mamicode.com
首页 > Web开发 > 详细

jQuery addClass() 源码解读

时间:2015-02-07 21:32:45      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

    addClass: function( value ) {
        var classes, elem, cur, clazz, j,
            i = 0,
            len = this.length,
            proceed = typeof value === "string" && value;

        if ( jQuery.isFunction( value ) ) {
            return this.each(function( j ) {
                jQuery( this ).addClass( value.call( this, j, this.className ) );
            });
        }

        if ( proceed ) {//如果传入的值不是字符串
            // The disjunction here is for better compressibility (see removeClass)
            //如果传入的是假值,"".match()  
            //core_rnotwhite 用于匹配非空格字符,且有g标识,匹配成功返回数组,匹配不成功返回[]
            classes = ( value || "" ).match( core_rnotwhite ) || [];
            //rclass = /[\t\r\n\f]/g
            for ( ; i < len; i++ ) {
                elem = this[ i ];
                //如果elem是元素,cur会返回真值," "或者 " a b "
                //替换tab符 回车 换行 换页 
                cur = elem.nodeType === 1 && ( elem.className ?
                    ( " " + elem.className + " " ).replace( rclass, " " ) :
                    " "
                );
                if ( cur ) {
                    j = 0;
                    //遍历,如果原始class中不存在,字符串拼接
                    while ( (clazz = classes[j++]) ) {
                        if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
                            cur += clazz + " ";
                        }
                    }
                    elem.className = jQuery.trim( cur );//最后两边去空格

                }
            }
        }

        return this;
    }

removeClass与addClass代码类似。

 

jQuery addClass() 源码解读

标签:

原文地址:http://www.cnblogs.com/qianlegeqian/p/4279278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!