簡述jq中attr()和prop()的區別

attr,prop都是屬性的意思,那他們有什麼區別呢?咱們先來看一下jquery的部分源碼:html

attr部分:node

 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部分:jquery

 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屬性節點的頻率。dom

你們知道,有的瀏覽器只要寫checked,disabled就能夠了,而有的則須要些checked=「checked」,disabled=「disabled」。好比用attr來獲取checked,選中狀態獲取attr(「checked」)爲checked,沒有選中則爲undefined。。而prop來獲取的爲,選中爲true,沒有選中爲false。spa

另外,用prop來設置屬性名,html結構是不會發生變化的。而用attr來設置屬性名,html結構是會發生變化的。.net

總的來講,按照我本身的理解,通常若是是標籤自身自帶的屬性,咱們用prop方法來獲取;若是是自定義的屬性,咱們用attr方法來獲取。code

 

參考連接:http://www.jb51.net/article/51688.htmorm

相關文章
相關標籤/搜索