Attribute和Property的區別
今天我們來掰扯掰扯attribute
和property
的區別,搞開發的人可能都見過這兩個單詞,但是他們在程式設計中到底有什麼區別呢?我們先來看一篇老外的文章:
翻譯自:http://lucybain.com/blog/2014/attribute-vs-property/
attribute
和property
的區別是什麼?
什麼是property
?
JS DOM物件都擁有property
,這些property
是一種類似於特定元素的例項變數之類的東西。比如,一個property
可以是各種不同的型別(boolean
, string
等等)。property
可以通過jQuery
的prop
方法來進行訪問(詳見下面的程式碼),也可以通過vanilla JS
我們來看一下下面這段程式碼:
<a href='page2.html' class='link classes' name='linkName' id='linkID'>Hi</a> $('#linkID').prop('href'); // returns "http://example.com/page2.html" $('#linkID').prop('name'); // returns "linkName" $('#linkID').prop('id'); // returns "linkID" $('#linkID').prop('className'); // returns "link classes"
a
標籤中所有的屬性都可以通過prop
方法來獲取,甚至是我們並沒有在標籤中指定的屬性
prop
方法也可以用來更新標籤中的屬性值,程式碼如下:
<a href='page2.html'>Hi</a>
$('#linkID').prop('href', 'page1.html');
$('#linkID').prop('href'); // returns "http://example.com/page1.html"
什麼是attribute
?
屬性存在於HTML
本身,而不是在DOM
中(其實我也不太明白作者是幾個意思????)
它和property
非常相似,但並不完全相同,當有一個可用的property
property
而不是attributes
如果你使用attr
去獲取一個標籤的attr
,那你真的會得到這個標籤(你會得到這個標籤本身的字串????),也就是說attribute
僅僅能獲取string'
(字串)屬性,程式碼如下:
<input type="checkbox" checked=true/>
$('input').prop('checked'); // returns true
$('input').attr('checked'); // returns "checked"
如果一個元素擁有一個預設值,那麼attr
方法就會獲得這個元素的預設值,即使這個元素的值被更新樂,程式碼如下:
<input type="text" name="username" value="user123">
$('input').prop('value', '456user');
$('input').prop('value'); // returns "456user"
$('input').attr('value'); // returns "user123"
當標籤中沒有關聯的property
時,我們可以使用attribute
來設定自定義屬性,程式碼如下:
<input type="text">
$('input').attr('customAttribute', 'something custom');
$('input').attr('customAttribute'); // returns "something custom"
$('input').prop('customAttribute'); // returns undefined
注意,在上面的程式碼中,使用prop
方法無法獲取到attr
方法設定的屬性值
同理,我們也可以用prop
來設定自定義屬性,但是attr
也一樣無法獲取該屬性:
<input type="text">
$('input').prop('customAttribute', 'something custom');
$('input').prop('customAttribute'); // returns "something custom"
$('input').attr('customAttribute'); // returns undefined
今天先寫到這兒吧