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
(type
和value
)
瀏覽器解析這個程式碼之後,一個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
,type
和value
這幾個properties:
id
property對於id
attribute來說是一個反射的property:獲取property會讀取attribute的值,設定property會寫入attribute的值。id
是一個純粹的反射的property,它不會修改和限制這個值。type
property對於type
attribute來說是一個反射的property:獲取property會讀取attribute的值,設定property會寫入attribute的值。type
<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反射輸入框中當前的文字內容,而value
attribute包含了HTML程式碼中value
attribute的初始
的文字內容。
如果你想要知道當前輸入框中是什麼內容,那就讀取property。如果你想要知道文字框的初始內容是什麼,則讀取attribute。或者你可以使用defaultValue
property,它是value
attribute純粹的反射:
1 | theInput.value // returns "John" |
有些properties可以直接反射attribute(rel,id),有些直接反射但名稱會略有不同(htmlFor
反射了for
attribute,className
反射了class
attribute),有些反射了它們的attribute但有一些限制(src,href,disabled,multiple)等等。這個文件說明了各種的反射型別。