您的位置:首页 > Web前端 > JQuery

jQuery addClass() 源码解读

2015-02-07 20:36 501 查看
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、hasClass与addClass代码类似。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: