阅读 116

attribute 和 property 的区别

前言

attribute 是 HTML 标签上的特性,也就是 html 代码中经常看到的键值对

property 是 DOM 中的属性,是 JavaScript 里的对象

示例

attribute 会始终保持 html 代码中的初始值, 而 Property 是有可能变化的.

 <input id="the-input" type="typo" value="Name:" customAttr="customAttr" />  // 在页面加载后,在input中输入 "Jack" // type 属性给的值为 typo,并不属于 input 支持的 type 种类 input.getAttribute('id') // the-input input.getAttribute('type') // typo input.getAttribute('value') // Name: input.getAttribute("customAttr") // customAttr input.id // the-input input.type // text input.value // Jack inout.customAttr // undefined 复制代码

在 attribute 中,值仍然是 html 代码中值,而在 property 中,type 被修正为 text,value 的值也随用户输入而对应改变。

可以成功的获取自定义的 attribute ,但是无法获取 property。

DOM 节点在初始化的时候会将 html 规范中定义的 attribute 赋值到 property 上。而自定义的 attribute 并不属于这个范围内,自然生成的 DOM 节点就没有这个 property。

区别

Attribute
  • 值只能为 string 类型

  • 如果编辑 HTML 时设置了元素的 attribute 值,之后就算改了这个值,attribute 依旧是默认的值。

  • 允许创建自定义的值

property
  • 值可以是多种类型:boolean,string,number等都可以

  • 可以通过 DOM 对象访问

  • 或许不到规定属性以外的自定义属性


作者:Sport
链接:https://juejin.cn/post/7020572679421820958


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐