Why should I prepend my custom attributes with “data-”?

北城以北 提交于 2019-11-26 17:55:44
Lachlan Hunt

There are several benefit for keeping custom attributes prefixed with data-*.

  1. It guarantees there will not be any clashes with extensions to HTML in future editions. This is a problem that has been encountered to some degree already with some of the new attributes introduced in HTML5, where existing sites were using attributes with the same name and expecting different and incompatible, custom behaviour. (e.g. the required attribute on input elements is known to have had some clashes on some popular websites in the past)

  2. There is a convenient DOM API, HTMLElement.dataset, for accessing these attributes from scripts. It is now supported in most browsers.

  3. They provide a clear indication of which attributes are custom attributes, and which ones are standardised attributes. This not only helps validators by allowing them to permit any attribute with data-* while still performing useful error checking for other attributes (e.g. to catch typos), it also helps make this aspect of the source code clearer to those reading it, including people who may work on a website after the original author.

According to John Resig, the whole purpose of the addition of these custom data attributes to the HTML5 sepcs is to allow to embed custom data in HTML while still being valid.

If you don't care about validation (and, as you said, your custom attributes are not colliding with existing HTML attributes like name, id, style, etc.), then I guess you don't have to use the data- prefix. But considering that this is not a huge cost for writing valid, compatible code, I don't see why you wouldn't do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!