您可以定义自己的 HTML 元素属性吗?
我想知道您是否可以在 HTML 中定义自己的属性。例如,在 HTML div 中,有一系列属性,例如 style
、title
、class
等。您可以编写并添加自己的属性吗?同时保持语法正确?
例如:
对此的需要是关于 Javascript 和数据的。
I was wondering if you can define your own attributes in HTML. For example in HTML divs there's a range of attributes, such as style
, title
, class
etc. Can you make up and add your own, while remaining syntactically correct?
For example: <div class="example" test_item="20"></div>
The need for this is with regards to Javascript and data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
但有一个例外——没有。 HTML 使用规范定义的属性和元素,并且仅使用这些属性和元素。
该例外是 名称以
data-
开头,并且仅当您遵循 HTML 5 草案时才如此。也就是说,在
id
或class
属性中对数据进行编码通常是合适的。With one exception — no. HTML uses the attributes and elements defined by the specification, and only those attributes and elements.
That exception is attributes with names starting
data-
, and then only if you are following the HTML 5 draft.That said, it is often appropriate to encode the data in the
id
orclass
attribute.您可以按如下方式为任何元素定义数据属性,并使用 jQuery 数据方法轻松检索这些属性。
You can define the data attribute for any element as follows, and use jQuery data method to retrieve those attributes easily.
语法正确——否;但是,jQuery 将毫无问题地读取您添加到 HTML 标记的任何属性。
Syntactically Correct -- NO; however, jQuery will read any attribute you add to an HTML tag without any problem.
根据记录,您可以使用 setAttribute("name","value") 将任何您想要的属性添加到带有 javascript 的元素中,
并且效果很好。这也主要是跨浏览器的: quirksmode
for the record you can add any attribute you want to an element with javascript using setAttribute("name","value")
and it works fine. This is also mostly cross browser: quirksmode