data-* - HTML: HyperText Markup Language 编辑

The data-* global attributes form a class of attributes called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation by scripts.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

All such custom data are available via the HTMLElement interface of the element the attribute is set on. The HTMLElement.dataset property gives access to them.
The * may be replaced by any name following the production rule of XML names with the following restrictions:

  • the name must not start with xml, whatever case is used for these letters;
  • the name must not contain any semicolon (U+003A);
  • the name must not contain capital letters.

Note that the HTMLElement.dataset property is a DOMStringMap, and the name of the custom data attribute data-test-value will be accessible via HTMLElement.dataset.testValue (or by HTMLElement.dataset["testValue"]) as any dash (U+002D) is replaced by the capitalization of the next letter, converting the name to camelcase.

Usage

By adding data-* attributes, even ordinary HTML elements can become rather complex and powerful program-objects. For example, a space-ship "sprite" in a game could be a simple <img> element with a class attribute and several data-* attributes:

<img class="spaceship cruiserX3" src="shipX3.png"
  data-ship-id="324" data-weapons="laserI laserII" data-shields="72%"
  data-x="414354" data-y="85160" data-z="31940"
  onclick="spaceships[this.dataset.shipId].blasted()">

For a more in-depth tutorial about using HTML data attributes, see Using data attributes.

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'data-*' in that specification.
Living StandardNo change from latest snapshot, HTML 5.1
HTML 5.1
The definition of 'data-*' in that specification.
RecommendationSnapshot of HTML Living Standard, no change from HTML5
HTML5
The definition of 'data-*' in that specification.
RecommendationSnapshot of HTML Living Standard, initial definition.

Browser compatibility

BCD tables only load in the browser

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:63 次

字数:6629

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文