简体   繁体   English

将自定义属性添加到HTML标签

[英]Adding custom attributes to HTML tags

I have been using data attributes to add custom attributes in HTML. 我一直在使用数据属性在HTML中添加自定义属性。 Unfortunately data is not supported in older browsers. 不幸的是,较旧的浏览器不支持数据。

As an alternative, what is the disadvantage of creating custom attributes in HTML? 或者,在HTML中创建自定义属性的缺点是什么?

As an example I created carType = 'nissa' as an attribute in HTML, and I was able to parse it with javascript utilizing element.getAttribute(attributename) 作为示例,我创建了carType = 'nissa'作为HTML中的属性,并且我能够使用element.getAttribute(attributename)用javascript对其进行解析element.getAttribute(attributename)

It seems to work in every browser I have tested. 它似乎可以在我测试过的所有浏览器中使用。 What is the negative side to this workflow? 这个工作流程的负面影响是什么?

data- attributes are supported even in older browsers. 即使在较旧的浏览器中也支持data-属性。 (see the Note) (请参阅注释)

You can simply get them using the way you described: 您可以使用描述的方式简单地获取它们:

element.getAttribute('data-xy')

The negative side of using non-standard attributes is that they make your HTML invalid. 使用非标准属性的不利方面是它们会使HTML无效。 Validation is a very useful tool for finding problems in your markup. 验证是一种在标记中发现问题的非常有用的工具。 If you use the HTML5 doctype (you can safely do even in old browsers) using data- attributes will help you keep your markup valid. 如果您使用HTML5文档类型 (即使在旧的浏览器中也可以放心使用),则使用data-属性将帮助您保持标记有效。

More information on MDN 有关MDN的更多信息

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

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