最佳实践:以类或数据属性作为标识符 [英] Best practice: class or data attribute as identifier
问题描述
我发现它有两种可能性:
/ p>
- 要么向我的元素添加一个css类,这不一定对应于任何现有的css规则:
< ; div class =validation-required>< / div>
- 或者我使用如下的数据属性:
< div data-validation-required>< / div>
2012年使用R#),如果我使用第一种方法,我收到警告说我不应该使用未定义的css类。这让我相信这可能不是最好的主意。然而,这是我最常使用的方法,尽管这可能只是我们可以使用数据属性之前的一段时间。
所以我的问题非常简单,我应该怎样简单地标记一个元素以便进一步处理?
感谢您的任何回答
PS:我意识到这个问题可能容易出现主观意见,但我确实希望在现代浏览器中使用什么是一致的。
PPS:我已经完成了对这个问题的搜索,但是大多数问题都是关于性能的,这并不是我一次性关注的主要问题。
根据W3C
data- *
自定义数据属性用于存储pag私有的自定义数据e或应用程序,对此没有更多适当的属性或元素。
这些属性不适用于独立于使用属性的站点的软件。
class属性在HTML中有几个角色:作为样式表选择器(当作者希望将样式信息分配给一组元素时)。
如果您使用 class
属性,您可以从本地 getElementsByClassName 搜索和 classList
对象获得切换,添加和删除类。 没有什么像 请参阅Oliver Moran的评论 getElementsByAttributeValue
,您需要迭代。
$ b
另一方面,如果您需要存储多个数据,则可以使用 dataset属性。
所以如果你想搜索或者数据是否影响元素的外观,我会使用 class
。如果您需要存储多个数据,那么数据
会更合适。
Lately I've been wondering what the best way to go is to perform javascript actions on multiple elements.
The way I see it there are 2 possibilities:
- Either I add a css class to my elements, which doesn't necessarily correspond to any existing css rules:
<div class="validation-required"></div>
- Or I use a data-attribute like so:
<div data-validation-required></div>
In my IDE (Visual studio 2012 using R#), if I use the first method, I get a warning saying I shouldn't use css-classes which aren't defined. Which makes me believe this might not be the best idea anyway. However, this is the method I've most-often seen used, though this might just be a relic from days before we could use the data- attribute.
So my question is pretty simple, which way should I go to simply "tag" an element for further processing?
Thanks for any answers
PS: I realize this question might be prone to subjective opinions, though I do hope there is a concensus on what to use in modern-day browsers.
PPS: I've done a search on this matter, but most questions are about performance, which isn't my primary concern for one-off situations.
According to W3C
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements. These attributes are not intended for use by software that is independent of the site that uses the attributes.
The class attribute has several roles in HTML: As a style sheet selector (when an author wishes to assign style information to a set of elements). For general purpose processing by user agents.
If you use class
attribute, you can benefit from native getElementsByClassName
searching andclassList
object for toggling, adding and removing class. There's nothing like See Oliver Moran's commentgetElementsByAttributeValue
, you need to iterate.
On the other hand, if you need to store multiple data, you can use dataset attribute.
So if you want searching or if the data affect the look of the element, I would use class
. If you need to store multiple data, the data
would be more appropriate.
这篇关于最佳实践:以类或数据属性作为标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!