jQuery源码分析13: .addClass, .removeClass, .hasClass
描述:
.addClass( className )
classNameOne or more class names to be added to the class attribute of each matched element.
.addClass( function(index, currentClass) )
function(index, currentClass)A function returning one or more space-separated class names to be added. Receives the index position of the element in the set and the old class value as arguments.
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
addClass: function( value ) {
var classNames, i, l, elem, setClass, c, cl;
/**
* .addClass( function(index, currentClass) )
* 遍历匹配的jQuery对象,将函数的返回值作为类名添加到class属性
*/
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
/**
* .addClass( className )
* 遍历匹配的jQuery对象,将className添加到class属性
*/
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
//< 将第i个匹配的jQuery对象转化成DOM对象
//< 匹配的元素必须是元素节点
//< 若它的className为空且className数组长度为1,则直接将value赋值给className
//< 否则遍历每一个className,判断是否已存在于该元素的class属性值中,若不存在则添加
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
同理可参考removeClass源码
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},