PHP,DDD,CQRS,Event Sourcing,Kubernetes,Docker,Golang

0%

HTML中的properties和attributes有什么区别?

当写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