1. 程式人生 > >Attribute和Property的區別

Attribute和Property的區別

今天我們來掰扯掰扯attributeproperty的區別,搞開發的人可能都見過這兩個單詞,但是他們在程式設計中到底有什麼區別呢?我們先來看一篇老外的文章: 翻譯自:http://lucybain.com/blog/2014/attribute-vs-property/

attributeproperty的區別是什麼?

什麼是property? JS DOM物件都擁有property,這些property是一種類似於特定元素的例項變數之類的東西。比如,一個property可以是各種不同的型別(booleanstring等等)。property可以通過jQueryprop方法來進行訪問(詳見下面的程式碼),也可以通過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

今天先寫到這兒吧