問題描述
所以我使用的任何自定義數據屬性都應該以data-"開頭:
So any custom data attribute that I use should start with "data-":
<li class="user" data-name="John Resig" data-city="Boston"
data-lang="js" data-food="Bacon">
<b>John says:</b> <span>Hello, how are you?</span>
</li>
如果我忽略這一點,會有什么不好的事情發生嗎?即:
Will anything bad happen if I just ignore this? I.e.:
<li class="user" name="John Resig" city="Boston"
lang="js" food="Bacon">
<b>John says:</b> <span>Hello, how are you?</span>
</li>
我想一件壞事是我的自定義屬性可能與具有特殊含義的 HTML 屬性沖突(例如,name
),但除此之外,只寫example_text"是否有問題數據示例文本"?(它不會驗證,但誰在乎呢?)
I guess one bad thing is that my custom attributes could conflict with HTML attributes with special meanings (e.g., name
), but aside from this, is there a problem with just writing "example_text" instead of "data-example_text"? (It won't validate, but who cares?)
推薦答案
保持自定義屬性以 data-* 為前綴有幾個好處.
There are several benefit for keeping custom attributes prefixed with data-*.
它保證在以后的版本中不會與 HTML 的擴展發生任何沖突.這是一個在某種程度上已經在 HTML5 中引入的一些新屬性遇到的問題,其中現有站點使用具有相同名稱的屬性并期望不同且不兼容的自定義行為.(例如,已知
input
元素上的required
屬性在過去曾在一些流行網站上發生過沖突)
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 oninput
elements is known to have had some clashes on some popular websites in the past)
有一個方便的 DOM API,HTMLElement.dataset,用于從腳本訪問這些屬性.現在大多數瀏覽器都支持.
There is a convenient DOM API, HTMLElement.dataset, for accessing these attributes from scripts. It is now supported in most browsers.
它們清楚地表明哪些屬性是自定義屬性,哪些是標準化屬性.這不僅通過允許驗證器允許具有 data-* 的任何屬性同時仍然對其他屬性執行有用的錯誤檢查(例如捕獲拼寫錯誤)來幫助驗證器,它還有助于使源代碼的這一方面對閱讀它的人來說更加清晰,包括人們誰可以在原作者之后在網站上工作.
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.
這篇關于為什么我應該在我的自定義屬性前面加上“data-"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!