本篇較為詳細地分析 jQuery 源碼中的 removeClass() 方法,搭配程式碼示範供參考。removeClass() 與 addClass() 差異不大,一起來看看:
jQuery.fn.extend({
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
//未傳參數或傳入非空字串時 proceed 為真。
proceed = arguments.length === 0 || typeof value === "string" && value;
//若 value 是 Function,則依回傳的類名再次呼叫 removeClass 自身。
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
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;
//與 addClass 的關鍵差異:檢索到要移除的類名時,用 replace 替換成空白。
while ( (clazz = classes[j++]) ) {
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
//另一個關鍵差異:若未傳 value,finalValue 為空字串,會移除該元素的所有類名;
//若傳了 value,則移除匹配的類名後,把剩餘類名 trim 後設回 className。
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
return this;
}
});
相較於 addClass 的「檢查後添加」,removeClass 的關鍵在於用 while 迴圈反覆 replace 掉目標類名,並在未傳參數時一次清空所有類名,希望這份解析對你的開發有所幫助。