• 周六. 5月 4th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

properties 和 attributes的区别

admin

11月 28, 2021

在编写HTML源代码时,可以在HTML元素上定义属性(attribute)。然后,一旦浏览器解析了您的代码,就会创建一个相应的DOM节点。该节点是一个对象,因此它具有属性(properties )。

比如:<input type="text" value="Name:"> 

它有两个attributes,type和value。一旦浏览器解析了这段代码,就会创建一个HTMLInputElement对象,该对象将包含几十个properties,比如:accept、accessKey、align、alt、attributes、autofocus、baseURI、checked、childElementCount、childNodes、children、classList、className、clientHeight等。

对于给定的DOM节点对象,properties 是该对象的属性,而attributes是该对象的attributes属性的元素。相应的DOM节点将具有id、类型和值的properties(等等)。以下用英文比较好理解

  • The id property is a reflected property for the id attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id is a pure reflected property, it doesn’t modify or limit the value.

  • The type property is a reflected property for the type attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type isn’t a pure reflected property because it’s limited to known values (e.g., the valid types of an input). If you had <input type="foo">, then theInput.getAttribute("type") gives you "foo" but theInput.type gives you "text".

  • In contrast, the value property doesn’t reflect the value attribute. Instead, it’s the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs "John" into the input box, then:

    theInput.value // returns "John"
    

    whereas:

    theInput.getAttribute('value') // returns "Name:"
  • value properties 反映输入框中的当前文本内容,而value attributes包含来自HTML源代码的value属性的初始文本内容。因此,如果你想知道当前文本框中有什么,读取properties 。但是,如果您想知道文本框的初始值是多少,请读取attributes。或者您可以使用defaultValue属性,它是value attributes的纯粹反映
  • theInput.value                 // returns "John"
    theInput.getAttribute('value') // returns "Name:"
    theInput.defaultValue          // returns "Name:"
  • 有几个properties 直接反映了它们的attributes(rel, id),有些是直接反映了稍微不同的名称(htmlFor反映了for attribute,className反映了class attribute),许多properties 反映了它们的attributes,但有限制/修改(src, href, disabled, multiple),等等。该规范涵盖了各种反射。
  • disabled是一个特殊的属性,比如一个button的disabled properties 默认是false,这个按钮就是启用的。当你添加disabled attributes时,会将properites的disabled转化为true,这个按钮就被禁用了。 添加或者删除disabled attributes会禁用或启用按钮 ,但是这个disabled的值是true或者false是没意义的。所以<button disabled=”false”>Still Disabled</button>.的按钮还是禁用的。想改变按钮启用或禁用状态,要改变disabled properties,这就是properties存在的意义!(但是用Vue的项目中,标签上用(v-bind):disabled=”false”j就是有效的,会禁用按钮,这是因为Vue的v-bind内部做了处理)
  • The HTML attribute and the DOM property are not the same thing, even when they have the same name.

《properties 和 attributes的区别》有一个想法

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注