Attributes and properties

当浏览器加载页面,它“读取”(换句话说:“解析”)HTML并从中生成DOM对象时。对于元素节点来说,大多数标准HTML attributes自动成为DOM对象的 properties

例如,如果有个标签是 <body id="page">,那么DOM对象会有 body.id="page"

但是 attribute-property 映射不是一一对应的! 在本章中,我们将注意区分这两个概念,看看如何使用它们,何时它们是相同的,何时还是不同的。

DOM properties

我们已经看到了内置的DOM properties, 有很多。但技术上没有人限制我们,如果不够,我们可以添加我们自己的。

DOM节点是常规的JavaScript对象。我们可以改变它们。

例如,让我们在 document.body 中创建一个新 property :

document.body.myData = {name: 'Caesar',title: 'Imperator'
};alert(document.body.myData.title); // Imperator

我们也可以添加一个方法:

document.body.sayTagName = function() {alert(this.tagName);
};document.body.sayTagName(); // BODY (the value of "this" in the method is document.body)

我们还可以修改像 Element.prototype 这样的内置原型, 并且向所有元素添加新的方法:

Element.prototype.sayHi = function() {alert(`Hello, I'm ${this.tagName}`);
};document.documentElement.sayHi(); // Hello, I'm HTML
document.body.sayHi(); // Hello, I'm BODY

因此,DOM properties 和方法的行为与常规JavaScript对象类似:

  • 它们可以有任何价。
  • 它们是区分大小写的(是 elem.nodeType, 而不是 elem.NoDeTyPe )。

HTML attributes

在HTML中,标签可能有 attributes。当浏览器解析HTML并创建DOM对象时,它识别标准 attributes 并根据这些 attributes 创建DOM properties

例如:

<body id="test" something="non-standard"><script>alert(document.body.id); // test// 非标准attribute不会产生propertyalert(document.body.something); // undefined</script>
</body>

请注意,一个元素的标准 attribute 对另一个元素可能是未知的。例如,"type"是 <input> 的标准 attribute,但不是 <body> 的标准 attribute。标准 attributes 在相应元素类的规范中进行了描述。

<body id="body" type="..."><input id="input" type="text"><script>alert(input.type); // textalert(body.type); // undefined: DOM property 没有创建, 因为这是非标准的</script>
</body>

因此,如果一个 attribute 是非标准的,那么它就不会有一个DOM-property。有办法访问这些属性吗?

当然有。所有 attributes 都可以通过以下方法访问:

  • elem.hasAttribute(name) – 检查存在。
  • elem.getAttribute(name) – 得到值。
  • elem.setAttribute(name, value) – 设置值。
  • elem.removeAttribute(name) – 移除 attribute。

这些方法与HTML中编写的内容完全一致。

还可以使用 elem.attributes 读取所有 attributes : 属于内置 Attr 类, 具有 namevalue properties 的对象集合。

下面是一个读取非标准 property 的演示:

<body something="non-standard"><script>alert(document.body.getAttribute('something')); // non-standard</script>
</body>

HTML attributes 具有以下特点:

  • 名称不区分大小写( id 与 ID 相同)。

  • 它们的值总是字符串。

下面是一个使用 attributes 的扩展演示:

<body><div id="elem" about="Elephant"></div><script>alert( elem.getAttribute('About') ); // (1) 'Elephant', 读elem.setAttribute('Test', 123); // (2), 写alert( elem.outerHTML ); // (3), 查看这个attribute是否存在HTML中(yes)for (let attr of elem.attributes) { // (4) list allalert( `${attr.name} = ${attr.value}` );}</script>
</body>

请注意:

  • getAttribute('About') – 第一个字母在这里是大写的,而在HTML中都是小写的。但这并不重要: attribute 名是不区分大小写的。
  • 我们可以给一个 attribute 赋值任何东西,但它会变成一个字符串。所以这里我们有 “123” 作为值。
  • 所有的 attributes,包括我们设置的 attributes,都在 outerHTML 中可见。
  • attributes 集合是可迭代的,并将元素的所有 attributes (标准的和非标准的) 作为具有 namevalue properties 的对象。

Property-attribute 同步

当一个标准 attribute 发生变化时,相应的 property 会自动更新,反之亦然(有些例外)。

在下面的示例中,id 作为一个 attribute 被修改,我们可以看到 property 也发生了改变。反之亦然:

<input><script>let input = document.querySelector('input');// attribute => propertyinput.setAttribute('id', 'id');alert(input.id); // id (updated)// property => attributeinput.id = 'newId';alert(input.getAttribute('id')); // newId (updated)
</script>

但也有例外,比如 input.value 只从 attributeproperty 同步,而不会反向同步:

<input><script>let input = document.querySelector('input');// attribute => propertyinput.setAttribute('value', 'text');alert(input.value); // text// NOT property => attributeinput.value = 'newValue';alert(input.getAttribute('value')); // text (not updated!)
</script>

在上面的示例说明:

  • 更改 attribute 值会更新 property
  • 但是 property 更改不会影响 attribute

这个“特性”实际上可能会派上用场,因为用户的操作可能会导致值的更改,在这些更改之后,如果我们想从HTML中恢复“原始”值,它就在 attribute 中。

DOM properties 是有类型的

DOM properties 并不总是字符串。例如,input.checkedproperty (用于复选框)是一个布尔值:

<input id="input" type="checkbox" checked> checkbox<script>alert(input.getAttribute('checked')); // attribute 值是: 空字符串alert(input.checked); // property 值是: true
</script>

还有其他的例子。 styleattribute 是一个字符串,但是 styleproperty 是一个对象:

<div id="div" style="color:red;font-size:120%">Hello</div><script>// stringalert(div.getAttribute('style')); // color:red;font-size:120%// objectalert(div.style); // [object CSSStyleDeclaration]alert(div.style.color); // red
</script>

不过,大多数 properties 都是字符串。

很少情况下,即使DOM property 类型是字符串,它也可能与 attribute 不同。例如,href 的 DOM property 总是一个完整的URL,即使该 attribute 是一个相对URL或只是一个 #shah

这里有一个例子:

<a id="a" href="#hello">link</a>
<script>// attributealert(a.getAttribute('href')); // #hello// propertyalert(a.href ); // full URL in the form http://site.com/page#hello
</script>

如果我们需要 href 或任何其他 attribute 的值完全符合HTML中所写的,我们可以使用 getAttribute

非标准 attributes 和 dataset

在编写HTML时,我们使用了很多标准 attributes 。但非标准的,定制的呢?首先,让我们看看它们是否有用? 对什么有用?

有时,非标准 attributes 用于将定制数据从HTML传递到 JavaScript,或者为JavaScript“标记”HTML元素。

像这样:

<!-- 标记此 div 用来显示 name -->
<div show-info="name"></div>
<!-- 这个显示 age -->
<div show-info="age"></div><script>// 该代码找到一个带有标记的元素,并显示所请求的内容let user = {name: "Pete",age: 25};for(let div of document.querySelectorAll('[show-info]')) {// 在字段中插入相应的信息let field = div.getAttribute('show-info');div.innerHTML = user[field]; // first Pete into "name", then 25 into "age"}
</script>

它们还可以用于 style 一个 元素。

例如,这里的订单状态使用了order-state 这个 attribute :

<style>/* 样式依赖于自定义属性 "order-state" */.order[order-state="new"] {color: green;}.order[order-state="pending"] {color: blue;}.order[order-state="canceled"] {color: red;}
</style><div class="order" order-state="new">A new order.
</div><div class="order" order-state="pending">A pending order.
</div><div class="order" order-state="canceled">A canceled order.
</div>

为什么使用 attribute 会比拥有像 .order-state-new.order-state-pending.order-state-canceled 这样的类更可取呢?

因为 attribute 更方便管理。状态可以很容易地改变:

// 比删除旧类/添加新类更简单
div.setAttribute('order-state', 'canceled');

但是自定义 attributes 可能存在一个问题。如果我们为了我们的目的使用一个自认为的非标准 attribute,但是标准已经引入了它,并让它做一些事情,那会怎样?HTML语言是活的,它在发展,越来越多的 attributes 似乎适合开发人员的需要。在这种情况下可能会有意想不到的效果。

为了避免冲突, data-* 这个 attributes 出现了。

所有以“data-”开头的 attributes 都保留给程序员使用。它们在dataset 这个 property中可用。

例如,如果一个 elem 有一个名为 "data-about" 的属性,它可以作为 element.dataset.about 使用。

像这样:

<body data-about="Elephants">
<script>alert(document.body.dataset.about); // Elephants
</script>

data-order-state 这样的多字 ``attributes会变成驼峰式的:dataset.orderState`。

下面是一个重写的 “order state” 示例:

<style>.order[data-order-state="new"] {color: green;}.order[data-order-state="pending"] {color: blue;}.order[data-order-state="canceled"] {color: red;}
</style><div id="order" class="order" data-order-state="new">A new order.
</div><script>// readalert(order.dataset.orderState); // new// modifyorder.dataset.orderState = "pending"; // (*)
</script>

使用 data-* attribute 是传递自定义数据的有效、安全的方式。

请注意,我们不仅可以读取数据 attribute,还可以修改 data-attributes 。然后CSS相应地更新视图: 在上面的例子中,最后一行 (*) 将颜色更改为蓝色。

总结

  • Attributes – 是HTML所写的内容。
  • Properties – 是DOM对象中的内容。

一个小的比较:

Properties Attributes
Type 任何值、标准 properties 都具有规范中描述的类型 字符串
Name 名称是区分大小写的 名称不区分大小写

处理属性的方法有:

  • elem.hasAttribute(name) – 检查存在。
  • elem.getAttribute(name) – 得到值。
  • elem.setAttribute(name, value) –设置值.
  • elem.removeAttribute(name) – 移除属性.
  • elem.attributes 所有 attributes 的集合.

对于大多数情况,最好使用DOM properties 。只有当DOM properties 不适合我们时,我们才应该引用 attributes ,例如:

  • 我们需要一个非标准 attribute。但如果它以 data- 开始,那么我们应该使用 dataset

  • 我们希望读取的值就是HTML中的“写入”内容。DOM property 的值可能不同,例如 href property 总是一个完整的URL,我们可能想要获得“原始”值。

Attributes and properties相关推荐

  1. Windows C++中__declspec(dllexport)的使用

    __declspec是Microsoft VC中专用的关键字,它配合着一些属性可以对标准C/C++进行扩充.__declspec关键字应该出现在声明的前面. __declspec(dllexport) ...

  2. jquery 1.6以上版本 全选

    2019独角兽企业重金招聘Python工程师标准>>> <html xmlns="http://www.w3.org/1999/xhtml"> < ...

  3. angular绑定数据_Angular中的数据绑定说明

    angular绑定数据 数据绑定 (Data Binding) 动机 (Motivation) Data often defines the look of an application. Inter ...

  4. python自动华 (十四)

    Python自动化 [第十四篇]:HTML介绍 本节内容: Html 概述 HTML文档 常用标签 2. CSS 概述 CSS选择器 CSS常用属性 1.HTML 1.1概述 HTML是英文Hyper ...

  5. 前端相关html和css

    #请参考http://www.cnblogs.com/pycode/p/5792142.html #html css 和js说明 ##1.什么是html? HTML(HyperText MarkUp ...

  6. 关于spring中commons-attributes-compiler.jar的使用问题

       昨天用spring做了个定时器,用于定时扫描某通讯公司外网ftp服务器的约定路径下是否有我需要的文件并下载到本公司服务器上.记得以前做过类似的一个定时器,觉得手到擒来的事情,没想到又折腾了大半天 ...

  7. Nature子刊:干旱条件下土壤细菌网络的稳定性不如真菌网络

    应对干旱,细菌崩了,真菌依然很稳 Soil bacterial networks are less stable under drought than fungal networks Nature C ...

  8. NC:应对干旱 细菌崩了 真菌依然很稳(纯网络分析发Nature子刊)

    文章目录 应对干旱,细菌崩了,真菌依然很稳 译者有话说 摘要 背景 结果 1. 细菌和真菌群落 图1. 细菌真菌群落对干旱的响应 2. 细菌和真菌网络 图2. 共丰度网络中OTU的相对丰度比例 图3. ...

  9. jquery 中attr和prop的区别

    在jQuery API中也有专门解释: Attributes VS. Properties 在一些特殊的情况下,attributes和properties的区别非常大.在jQuery1.6之前,.at ...

最新文章

  1. 公开课 | 旷视科技产品总监:计算机视觉如何赋能身份验证场景
  2. OI模板大全(普及~省选NOI)
  3. 一份火爆AI圈的高分深度学习入门讲义,李航、马少平领衔多位科学家力荐!...
  4. Analog使用中的一些技巧和总结
  5. 控件尺寸规范_微信小程序设计规范你了解多少
  6. 图像滤镜艺术---微软自拍APP滤镜实现合集DEMO
  7. 手机端测试时用的几个软件
  8. 头条账号权重被降低后会导致点赞推荐兑换率会下降
  9. 单片机C语言任何位置跳转到任何指定地址 -转
  10. Mysql分页之limit用法与limit优化
  11. VBA实例6 CorelDraw 批量生成设备位号、连续编号
  12. SQL 数据库 学习 004 预备知识
  13. 蓝桥杯赛后总结与反思
  14. 黑客攻击_我如何开始黑客攻击
  15. 乱谈SOA——IT世界观及方法论
  16. 几张图片生成3D模型?距离真正的AI建模还有多远?
  17. vue-element-admin 花裤衩 模板 ,中文版,运行报错解决方案
  18. vscode进行远程服务器 An SSH installation couldnt be found
  19. C语言中用do while解决阶乘之和问题
  20. python 遍历元组_python遍历元祖

热门文章

  1. CADWorx 应用感悟(一)设计流程
  2. Robotstudio软件二次开发:基于C#语言的Smart组件开发基础
  3. 信创操作系统--统信UOS桌面版(文件与目录管理:浏览、管理、查找、共享、解压缩等)
  4. MIT6.830-lab5-B+ Tree Index(数据库的索引B+树的搜索、插入、删除窃取、删除合并)
  5. 【山东日照seo招聘】网站SEO优化中注意哪些小细节?
  6. Java 数组最佳指南,快收藏让它吃灰
  7. JS+Echarts制作实时大屏
  8. 新手小白看过来,使用vue-cli 创建uniapp项目的步骤
  9. Autolab 电化学工作站操作规程
  10. Apache Camel源码研究之Intercept