本篇較為詳細地分析 jQuery 源碼中的 removeAttr() 方法,搭配程式碼示範供參考。
首先是擴充 jQuery 原型物件的方法:
jQuery.fn.extend({
//name,傳入要 DOM 元素要移除的屬性名。
removeAttr: function( name ) {
//使用 jQuery.fn 的 each 方法遍歷當前選擇器選擇的 jQuery 物件陣列,並回傳該物件以便鏈式調用。
return this.each(function() {
//調用 jQuery 的全局方法 removeAttr,傳入遍歷出的 DOM 物件 this 和要移除的屬性名 name。
jQuery.removeAttr( this, name );
});
}
});
接著是 jQuery 的全局方法 removeAttr:
jQuery.extend({
//elem 為遍歷出的每個 DOM 物件,value 為要移除的屬性名。
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
//rnotwhite 為 (/\S+/g),若 value 為空白則為 null;若 value 為 "title href",match 會回傳 ["title", "href"]。
attrNames = value && value.match( rnotwhite );
//若 attrNames 不為 null 且節點類型為 1,進入 if 區塊。
if ( attrNames && elem.nodeType === 1 ) {
//遍歷 attrNames 陣列,逐一取出屬性名。
while ( (name = attrNames[i++]) ) {
//若屬性名與 JS 關鍵字同名(如 for、class),替換為 htmlFor、className。
propName = jQuery.propFix[ name ] || name;
//若是布爾值屬性則特別處理。
if ( jQuery.expr.match.bool.test( name ) ) {
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
//移除布爾值屬性實際上是給它賦值 false。
elem[ propName ] = false;
} else {
//相容 IE9 以下,將 default-checked 轉為 defaultChecked 並賦值 false。
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
} else {
//非布爾值屬性,調用 jQuery 全局 attr 方法設置。
jQuery.attr( elem, name, "" );
}
//調用 DOM 原生的 removeAttribute 移除屬性。
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
}
});
關鍵字屬性修正與相關輔助方法:
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
}
});
jQuery.extend({
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^?:checked|selected$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
檢測 setAttribute 是否支援駝峰命名的屬性名(相容 IE6/7):
support.getSetAttribute = div.className !== "t";
檢測 input 是否支援 getAttribute("value")(僅 IE8):
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
檢測布爾值屬性清單:
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
matchExpr = {
"bool": new RegExp( "^(?:" + booleans + ")$", "i" )
},
透過這份源碼解析,可以更清楚 removeAttr() 在處理布爾屬性、關鍵字屬性與跨瀏覽器相容時的細節,希望對你的開發有所幫助。