jQuery prop和attr的區別
兩者對比 jquery方法 原理 適合情境 缺陷prop 解析原生propertyelement.property radio/checkbox select標籤等需要讀boolean和索引的場合 讀不到自訂屬性如<a my='I'/> my屬性讀不到attr 通過Attr API去讀取element.getAttribute(propertyName) 除prop情境外 可能讀不到boolean或一些索引值如checked,selectedIndex prop方法 例子 在控制台輸入 document.getElementsByTagName('a')[0].href 控制台輸出 "http://www.baidu.com/home/xman/show/liteoff" href就是標籤a映射的DOM對象HTMLAnchorElement的原生屬性。 jQuery源碼 複製代碼prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value );//這裡就是讀原生property } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }複製代碼 attr方法 例子 在控制台輸入 document.getElementsByTagName('a')[10].getAttribute('href') 控制台輸出 "http://www.hao123.com" getAttribute就是Attr類的查詢API。其他還有刪除、修改、增加。 jQuery源碼 attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name );//這裡通過Attr API讀取屬性 // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }