简体   繁体   English

数据属性有什么意义?

[英]What's the point of data attributes?

After reading the answers to this question , my mind feels like a melting ice cream cone. 在阅读了这个问题的答案后,我的思绪就像一个融化的冰淇淋蛋筒。

Considering the fact that you can assign arbitrary properties to DOM elements. 考虑到您可以为DOM元素分配任意属性。

eg 例如

 var myDiv = document.createElement('div'); myDiv.potato = ["puppies", "sea otters"] alert(myDiv.potato); 

What is the point of the whole data-* convention? 整个data-*惯例的重点是什么?

What advantage does it offer over assigning arbitrary properties? 分配任意属性有什么优势?

They are guaranteed not to conflict with real attributes (in current or future specifications). 保证它们不会与实际属性(在当前或未来的规范中)冲突。

They don't cause noise when validating markup. 验证标记时,它们不会产生噪音。

People maintaining your code who know HTML will know what sort of things a data-* attribute is used for and won't get confused trying to look up an attribute they might think they just hadn't heard about. 维护你的代码知道HTML的人会知道data-*属性用于什么类型的东西,并且不会混淆尝试查找他们可能认为他们没有听说过的属性。

Putting them in your HTML: 将它们放入HTML中:

<span data-tooltip="I will be processed by JavaScript and displayed in a tooltip,
    but because I am content, I belong in the HTML, so... here I am!">Hello!</span>

Making use of them in your CSS: 在CSS中使用它们:

<span data-number="1">Hello?</span>
[data-number]:before {content: attr(data-number) '. '}

And many more uses, but these are two that jump to mind immediately. 还有更多的用途,但这些是立刻想到的两个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM