attr,prop都是屬性的意思,那他們有什么區別呢?我們先來看一下jquery的部分源碼:
attr部分:
1 attr: function( elem, name, value, pass ) { 2 var ret, hooks, notxml, 3 nType = elem.nodeType; 4 // don't get/set attributes on text, comment and attribute nodes 5 if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { 6 return; 7 } 8 if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { 9 return jQuery( elem )[ name ]( value ); 10 } 11 // Fallback to prop when attributes are not supported 12 if ( typeof elem.getAttribute === "undefined" ) { 13 return jQuery.prop( elem, name, value ); 14 } 15 notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); 16 // All attributes are lowercase 17 // Grab necessary hook if one is defined 18 if ( notxml ) { 19 name = name.toLowerCase(); 20 hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); 21 } 22 if ( value !== undefined ) { 23 if ( value === null ) { 24 jQuery.removeAttr( elem, name ); 25 return; 26 } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { 27 return ret; 28 } else { 29 elem.setAttribute( name, value + "" ); 30 return value; 31 } 32 } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { 33 return ret; 34 } else { 35 ret = elem.getAttribute( name ); 36 // Non-existent attributes return null, we normalize to undefined 37 return ret === null ? 38 undefined : 39 ret; 40 } 41 }
prop部分:
1 prop: function( elem, name, value ) { 2 var ret, hooks, notxml, 3 nType = elem.nodeType; 4 // don't get/set properties on text, comment and attribute nodes 5 if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { 6 return; 7 } 8 notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); 9 if ( notxml ) { 10 // Fix name and attach hooks 11 name = jQuery.propFix[ name ] || name; 12 hooks = jQuery.propHooks[ name ]; 13 } 14 if ( value !== undefined ) { 15 if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { 16 return ret; 17 } else { 18 return ( elem[ name ] = value ); 19 } 20 } else { 21 if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { 22 return ret; 23 } else { 24 return elem[ name ]; 25 } 26 } 27 }
我們注意到,兩個方法最主要的源碼部分是:attr是通過setAtrribute和getAttribute來設置的,使用的是DOM屬性節點,而prop是通過document.getElementById(el)[name] = value來設置的,是轉化為js對象的屬性。
通常在獲取或者設置checked,selected,readonly,disabled等的時候使用prop效果更好,減少了訪問dom屬性節點的頻率。
大家知道,有的瀏覽器只要寫checked,disabled就可以了,而有的則需要些checked=“checked”,disabled=“disabled”。比如用attr來獲取checked,選中狀態獲取attr(“checked”)為checked,沒有選中則為undefined。。而prop來獲取的為,選中為true,沒有選中為false。
另外,用prop來設置屬性名,html結構是不會發生變化的。而用attr來設置屬性名,html結構是會發生變化的。
總的來說,按照我自己的理解,一般如果是標簽自身自帶的屬性,我們用prop方法來獲取;如果是自定義的屬性,我們用attr方法來獲取。
參考鏈接:http://www.jb51.net/article/51688.htm
