jQuery源码 — addClass方法

本方法定义在jQuery.prototype

addClass: function( value ) {
		var classNames, i, l, elem,
			setClass, c, cl;

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

		if ( value && typeof value === "string" ) {
			classNames = value.split( rspace );

			for ( i = 0, l = this.length; i < l; i++ ) {
				elem = this[ i ];

				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;
	}


发现一个转整型的好方法: ~~x
不论x是什么,基本都不会报错,实在不行就返回0,比如~~1.5,返回1

jQuery这里也用了~,这是一种取巧,即indexOf如果返回-1,~运算完正好为0,可以进行if判断,关于单个~运算,我试了几个数,感觉公式就是 -1 * ( 原值 + 1 )
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
	setClass += classNames[ c ] + " ";
}


我写一个通用的:
function addClass( el, className ) {
	var classNames = className.split(/\s/),
		curClass = trim(el.className),
		itemClass;
	if( !curClass && classNames.length === 1 ) {//如果el的className是空的,并且只传了一个className
		this.className = className;
	} else {
		for( var i = 0, len = classNames.length; i < len; i++ ){
			curClass = ' ' + curClass + ' ';	//这是为了进行下面的匹配
			itemClass = classNames[i];
			if( !~curClass.indexOf( ' ' + itemClass + ' ' )){
				curClass += classNames[i] + ' ';
			}
		}
		el.className = curClass;
	}
}

你可能感兴趣的:(addClass)