jQuery Access可以幫助我們操作DOM元素的屬性和樣式。以下是它的源代碼解析:
// Define access to element properties jQuery.each({ attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }); // Define attributes hook jQuery.attrHooks = { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } };
這是一個比較復雜的源碼,通過定義函數(shù)和鉤子來完成常見的元素屬性和樣式的操作。比如,如果我們要獲取一個元素的屬性值,首先會判斷它的節(jié)點類型,容錯一些不支持getAttribute方法的情況,然后根據(jù)屬性名獲取對應的鉤子,最后如果有鉤子,則調用它來獲取屬性值;否則,直接調用getAttribute方法獲取屬性值。