.addClass() 為匹配元素添加一個或多個類名,支持字符串、函數返回值、多類名空格分隔。源碼處理了函數參數、類名去重、性能優化等細節。
jQuery.fn.extend({
addClass: function(value) {
var classes, elem, cur, clazz, j, finalValue,
i = 0, len = this.length,
// 參數類型檢查:字符串或函數
proceed = typeof value === 'string' && value;
// 1. 函數參數:每個元素調用函數獲取類名
if (jQuery.isFunction(value)) {
return this.each(function(j) {
jQuery(this).addClass(value.call(this, j, this.className));
});
}
// 2. 字符串參數:解析類名數組
if (proceed) {
// rnotwhite = /\S+/g 匹配非空白序列
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;
// 遍歷要添加的類名
while ((clazz = classes[j++])) {
// 不存在才添加(去重)
if (cur.indexOf(' ' + clazz + ' ') < 0) {
cur += clazz + ' ';
}
}
// 去首尾空格
finalValue = jQuery.trim(cur);
// 僅在實際變化時賦值,避免觸發不必要的重繪
if (elem.className !== finalValue) {
elem.className = finalValue;
}
}
}
}
return this; // 鏈式調用
}
});
"a b"、函數 function(i, oldClass){ return 'c'; }、甚至陣列(隱式轉字符串)。match(rnotwhite) 提取所有非空白片段,自動處理多空格、換行分隔。' class1 class2 ',用 indexOf(' class ') 精確判斷是否存在。className 真正改變時賦值,減少瀏覽器重排/重繪。// 單個類名
el.classList.add('active');
// 多個類名 (ES6)
el.classList.add('a', 'b', 'c');
// 切換
el.classList.toggle('active');
// 批量操作數組
['a','b','c'].forEach(c => el.classList.add(c));
classList 為原生實現,無字符串解析開銷,API 語義清晰,推薦優先使用。