removeAttr() 是我們天天在用的方法,但真要問它內部處理了哪些邊界情況,很多人反而說不上來。翻開源碼會發現,這個看似簡單的方法其實照顧了布爾屬性、IE6/7 的駝峰命名問題以及多屬性傳參等一系列細節。
jQuery.fn.extend({
// name:要移除的屬性名
removeAttr: function( name ) {
// 遍歷當前選擇器選中的每個元素,並返回 jQuery 對象以支持鏈式調用
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
這層只做一件事:把集合裡每個 DOM 節點依次交給全局方法處理,然後回傳自身。
jQuery.extend({
removeAttr: function( elem, value ) {
var name, propName, i = 0,
// rnotwhite 即 /S+/g
// value 為 "title href" 時,attrNames 得到 ["title", "href"]
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
// for、class 這類關鍵字要換成 htmlFor、className
propName = jQuery.propFix[ name ] || name;
if ( jQuery.expr.match.bool.test( name ) ) {
// 布爾屬性:移除等同於賦值 false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
} else {
// 兼容 IE9 以下
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
} else {
jQuery.attr( elem, name, "" );
}
// IE6/7 不支持駝峰命名時,需用修正後的屬性名
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
}
});
多屬性支持。用 value.match(rnotwhite) 按空白拆分成數組,所以 removeAttr("title href") 這種寫法能一次移除多個屬性。
關鍵字修正。propFix 把 for 映射為 htmlFor、class 映射為 className,避開 JS 保留字衝突。
布爾屬性的特殊待遇。checked、selected 這類屬性在 DOM 裡並不是簡單的有無,而是對應屬性值為 true/false,所以源碼先把 elem[propName] 置為 false,再調用原生的 removeAttribute,兩步並行才能保證各瀏覽器行為一致。
IE 兼容探測。support.getSetAttribute 通過給一個新建 div 設置 className 再讀回來,判斷該瀏覽器是否支持駝峰命名的 setAttribute;support.input 則檢測能否信任 getAttribute("value")。這兩個布爾值決定了後面走哪條分支。
一個 removeAttr 背後是十幾年的瀏覽器差異沉澱。讀源碼的價值就在這裡:它會提醒你,看起來理所當然的 API,真實實現往往要處理大量你想不到的角落情況。