1. 程式人生 > 實用技巧 >HTML中的properties和attributes有什麼區別

HTML中的properties和attributes有什麼區別

[轉載]https://www.veitor.net/posts/What-is-the-difference-between-properties-and-attributes-in-HTML/


當寫HTML程式碼時,你可以在你的HTML元素中定義attributes,然後瀏覽器解析你的程式碼並建立一個對應的DOM節點。這個節點是一個Object,因此它具有properties

例如這是一個HTML元素:

1
<input type="text" value="Name:">

其擁有2個attributes(typevalue)

瀏覽器解析這個程式碼之後,一個HTMLInputElement

物件將會被建立,這個物件包含了很多的properties,如:accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight等。

對於DOM節點物件,properties就是這個物件的properties,而attributes是這個物件中名為attributes的property的元素。

當一個HTML元素被建立為DOM節點後,節點物件的許多properties與HTML元素中相同名稱或相似名稱的attributes有著關聯,但不是一對一的關係。例如這個HTML元素:

1
<input id="the-input" type="text" value="Name:">

對應的DOM節點物件具有id,typevalue 這幾個properties:

  • id property對於id attribute來說是一個反射的property:獲取property會讀取attribute的值,設定property會寫入attribute的值。id是一個純粹的反射的property,它不會修改和限制這個值。

  • type property對於type attribute來說是一個反射的property:獲取property會讀取attribute的值,設定property會寫入attribute的值。type

    不是一個純粹的反射的property,因為它被已知的值(如一個有效的input型別)限制了。如果你這麼寫<input type="foo">,則theInPut.getAttribute("type")將會返回給你foo,但theInput.type返回給你"text"

  • 相反的,value property不會反射 value attribute。而它就是輸入框的當前值。當用戶手動改變輸入框中的值時,value proerty將會反射這個改變,因此如果使用者輸入John到輸入框中:

1
theInput.value //returns "John"

1
theInput.getAttribute('value')//returns "Name:"

value property反射輸入框中當前的文字內容,而valueattribute包含了HTML程式碼中value attribute的初始的文字內容。

如果你想要知道當前輸入框中是什麼內容,那就讀取property。如果你想要知道文字框的初始內容是什麼,則讀取attribute。或者你可以使用defaultValue property,它是value attribute純粹的反射:

1
2
3
theInput.value                 // returns "John"
theInput.getAttribute('value') // returns "Name:"
theInput.defaultValue // returns "Name:"

有些properties可以直接反射attribute(rel,id),有些直接反射但名稱會略有不同(htmlFor反射了for attribute,className反射了class attribute),有些反射了它們的attribute但有一些限制(src,href,disabled,multiple)等等。這個文件說明了各種的反射型別。

原文:https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html