JS中attr和prop屬性的差異以及優先選擇範例介紹_基礎知識
比起attr,prop是1.6.1才新出來的,兩者從中文意思理解,都是取得/設定屬性的方法(attributes和properties)。只是,window或document中使用.attr()方法在jQuery1.6之前不能正常運行,因為window和document中不能有attributes。 prop應運而生了。
既然我們想知道他們兩的區別,最好就看看他們的源代碼,不要被代碼長度所嚇到,我們只看關鍵的幾句:
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 ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }
prop方法程式碼(jQuery版本1.8.3)
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 ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }
attr方法裡面,最關鍵的兩行程式碼,elem.setAttribute( name, value “” )和ret = elem.getAttribute( name ),很明顯的看出來,使用的DOM的API setAttribute和getAttribute方法操作的屬性元素節點。
而prop方法裡面,最關鍵的兩行程式碼,return ( elem[ name ] = value )和return elem[ name ],你可以理解成這樣document.getElementById(el)[name] = value,這是轉換成JS物件的一個屬性。
既然明白了原理是這樣,我們來看看一個例子:
<input type="checkbox" id="test" abc="111" />
$(function(){ el = $("#test"); console.log(el.attr("style")); //undefined console.log(el.prop("style")); //CSSStyleDeclaration对象 console.log(document.getElementById("test").style); //CSSStyleDeclaration对象 });
el.attr(“style”)輸出undefined,因為attr是取得的這個物件屬性節點的值,很明顯此時沒有這個屬性節點,自然輸出undefined
el.prop(“style”)輸出CSSStyleDeclaration對象,對於一個DOM對象,是具有原生的style對象屬性的,所以輸出了style對象
至於document.getElementById(“test”).style和上面那條一樣
接著看:
el.attr("abc","111") console.log(el.attr("abc")); //111 console.log(el.prop("abc")); //undefined
首先用attr方法為這個物件加入abc節點屬性,值為111,可以看到html的結構也改變了
el.attr(“abc”)輸出結果為111,再正常不過了
el.prop(“abc”)輸出undefined,因為abc是在這個的屬性節點中,所以透過prop是取不到的
el.prop("abc", "222"); console.log(el.attr("abc")); //111 console.log(el.prop("abc")); //222
我們再用prop方法為這個物件設定了abc屬性,值為222,可以看到html的結構是沒有變化的。輸出的結果就不解釋了。
上面已經把原理講清楚了,什麼時候用什麼就可以自己把握了。
提一下,在遇到要取得或設定checked,selected,readonly和disabled等屬性時,用prop方法顯然更好,例如像下面這樣:
<input type="checkbox" id="test" checked="checked" />
console.log(el.attr("checked")); //checked console.log(el.prop("checked")); //true console.log(el.attr("disabled")); //undefined console.log(el.prop("disabled")); //false
顯然,布林值比字串值讓接下來的處理更合理。
PS一下,如果你有JS效能潔癖的話,顯然prop的效能更高,因為attr需要存取DOM屬性節點,存取DOM是最耗時的。這種情況適用於多選項全選和反選的情況。
大家都知道有的瀏覽器只要寫disabled,checked就可以了,而有的要寫成disabled = "disabled",checked="checked",比如用attr("checked")獲取checkbox的checked屬性時選取的時候可以取到值,值為"checked"但沒選取取得值就是undefined。
jq提供新的方法「prop」來取得這些屬性,就是來解決這個問題的,以前我們使用attr獲取checked屬性時返回"checked"和"",現在使用prop方法獲取屬性則統一返回true和false。
那麼,什麼時候使用attr(),什麼時候使用prop()?
1.新增屬性名稱該屬性就會生效應該使用prop();
2.是有true,false兩個屬性使用prop();
3.其他則使用attr();
專案中jquery升級的時候大家要注意這一點!
以下是官方建議attr(),prop()的使用:
以下是官方建議attr(),prop()的使用:

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)
![如何解決'[Vue warn]: Missing required prop”錯誤](https://img.php.cn/upload/article/000/887/227/169304743965914.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
如何解決「[Vuewarn]:Missingrequiredprop」錯誤在開發Vue應用程式時,有時會遇到一個常見的錯誤訊息:「[Vuewarn]:Missingrequiredprop」。這個錯誤通常指的是元件中缺少必需的屬性值,導致元件無法正常渲染。解決這個問題的方法很簡單,我們可以透過一些技巧和規範來避免和處理這個錯誤。以下是一些解
![解決「[Vue warn]: Invalid prop: invalid value」錯誤的方法](https://img.php.cn/upload/article/000/465/014/169294628931912.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解決“[Vuewarn]:Invalidprop:invalidvalue”錯誤的方法在使用Vue.js開發應用程式時,我們經常會遇到一些錯誤和警告。其中一個常見的錯誤是「[Vuewarn]:Invalidprop:invalidvalue」。這個錯誤通常發生在我們嘗試將無效的值傳遞給Vue組件的屬性時。在本文中,我們將深入探討該錯誤的原
![如何解決'[Vue warn]: Invalid prop: type check”錯誤](https://img.php.cn/upload/article/000/887/227/169306085649427.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
如何解決“[Vuewarn]:Invalidprop:typecheck”錯誤Vue.js是一款流行的JavaScript框架,用於建立使用者介面。在使用Vue.js開發應用程式時,我們有時會遇到一些錯誤訊息,其中之一是「[Vuewarn]:Invalidprop:typecheck」。這個錯誤通常是由於我們在元件中錯誤使用了屬性
![解決「[Vue warn]: Avoid mutating a prop directly」錯誤的方法](https://img.php.cn/upload/article/000/465/014/169226406590115.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解決「[Vuewarn]:Avoidmutatingapropdirectly」錯誤的方法在使用Vue.js開發專案時,我們可能會遇到一個常見的警告訊息:「[Vuewarn]:Avoidmutatingapropdirectly」。這個警告訊息的意思是我們不應該直接改變一個props屬性的值,而是應該透過觸發事件,讓父元件去改變pro
![解決'[Vue warn]: Invalid prop: custom validator”錯誤的方法](https://img.php.cn/upload/article/000/000/164/169254319231018.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解決「[Vuewarn]:Invalidprop:customvalidator」錯誤的方法在使用Vue開發過程中,我們時常會遇到一些警告和錯誤訊息。其中一個常見的錯誤訊息就是「[Vuewarn]:Invalidprop:customvalidator」。這個錯誤訊息出現的原因是因為我們在使用自訂驗證器函數時,未能正確地驗證傳遞給元件
![如何處理「[Vue warn]: Avoid mutating a prop directly」錯誤](https://img.php.cn/upload/article/000/465/014/169224194948720.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
如何處理“[Vuewarn]:Avoidmutatingapropdirectly”錯誤當使用Vue.js開發Web應用程式時,我們經常會遇到一些警告或錯誤。其中一個常見的警告是“[Vuewarn]:Avoidmutatingapropdirectly”,這意味著我們在元件中直接修改了一個被父元件傳遞的屬性(prop)。在本文中,我們

Vue組件通訊中的多層級傳遞方案比較Vue是一款非常受歡迎的前端框架,它提供了一種組件化的開發方式,透過組件的嵌套和通訊,實現了複雜應用的開發。在實際開發中,元件之間的通訊常常是一個重要的問題。當元件之間存在多層級關係時,如何有效地傳遞資料成為了開發者需要思考的問題。本文將介紹幾種常見的多層級組件通訊方案,並對它們進行比較。使用props和$emitVue提
![解決「[Vue warn]: Invalid prop: update value」錯誤的方法](https://img.php.cn/upload/article/000/465/014/169305238381644.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
解決「[Vuewarn]:Invalidprop:updatevalue」錯誤的方法在Vue開發中,我們常常會遇到「[Vuewarn]:Invalidprop:updatevalue」錯誤。這個錯誤通常是由於父元件向子元件傳遞了一個無效的值所引起的。雖然這個錯誤是Vue的警告而不是致命錯誤,但還是應該及時解決,以確保程序的健全性。本文將介紹
