Javascript DOM:设置自定义DOM元素属性 [英] Javascript DOM: Setting custom DOM element properties

查看:362
本文介绍了Javascript DOM:设置自定义DOM元素属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在DOM元素上设置自定义属性,并依赖它们持久化吗?

Is it ok to set custom properties on DOM elements, and rely on them persisting?

例如,给定

 <html><body><div id="foo"></div></body></html>

执行 document.getElementById('foo')是公平的。 bar =baz; ,并期望 document.getElementsByTagName('div')[0] .bar 等于 baz

请注意,我正在谈论的属性与正常的JavaScript对象属性在这里,而不是元素属性。

Note that I'm talking about properties as in normal javascript object properties here, not element attributes.

我对跨浏览器的感兴趣,以及是否支持任何规范。

I'm interested both in how cross-browser it is, and whether its supported in any spec.

DOM API保证每次相同的DOM元素都会返回相同的JavaScript对象?

Does the DOM API guarantee that the same javascript object will be returned for the same DOM element every time?

推荐答案

作为一般规则, t使用自定义属性。您不应该以不期望的方式修改DOM对象,因为它们可能不会像您认为的那样。

As a general rule, don't use custom properties. You shouldn't modify DOM objects in ways they don't expect because they may not behave the way you think they will.

自定义属性是使用 data-前缀。

但是,HTML5并不是一个标准,并没有被广泛实现。但是如果您使用 set / getAttribute 数据 - 属性,它应该适用于所有合理的现代浏览器,并且将来不应使用数据库引入标准属性,

However, HTML5 is not a stanard and is not that widely implemented yet. But if you use set/getAttribute for data- attributes it should work on all reasonably modern browsers and no standard attribute should be introduced in the future with a data- prefix.

但是说到这里,我仍然建议使用自定义对象来存储值并通过元素 id 或或其他一些标准(如HTML 4.01)属性值。它避免了自定义属性和属性的问题,并且已知可以在任何地方使用。

But having said that, I would still recommend using a custom object to store the values and referencing them by element id or class or some other standard (as in HTML 4.01) attribute value. It avoids the issue of custom properties and attributes and is known to work everywhere.

这篇关于Javascript DOM:设置自定义DOM元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆