本文介绍了自定义属性 - 是还是不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我读到了越来越多的关于人们在 HTML 标签中使用自定义属性的信息,主要是为了嵌入一些额外的数据以在 javascript 代码中使用.

Recently I have been reading more and more about people using custom attributes in their HTML tags, mainly for the purpose of embedding some extra bits of data for use in javascript code.

我希望收集一些关于使用自定义属性是否是一种好的做法以及一些替代方法的反馈.

I was hoping to gather some feedback on whether or not using custom attributes is a good practice, and also what some alternatives are.

看起来它确实可以简化服务器端和客户端代码,但它也不符合 W3C.

It seems like it can really simplify both server side and client side code, but it also isn't W3C compliant.

我们是否应该在我们的网络应用程序中使用自定义 HTML 属性?为什么或为什么不?

Should we be making use of custom HTML attributes in our web apps? Why or why not?

对于那些认为自定义属性是一件好事的人:在使用它们时有哪些注意事项?

For those who think custom attributes are a good thing: what are some things to keep in mind when using them?

对于那些认为自定义属性不好的人:您使用哪些替代方法来完成类似的事情?

For those who think custom attributes are bad thing: what alternatives do you use to accomplish something similar?

更新:我最感兴趣的是各种方法背后的推理,以及为什么一种方法优于另一种方法的观点.我认为我们都可以想出 4-5 种不同的方法来完成同一件事.(隐藏元素、内联脚本、额外类、从 id 解析信息等).

Update: I'm mostly interested in the reasoning behind the various methods, as well as points as to why one method is better than another. I think we can all come up with 4-5 different ways to accomplish the same thing. (hidden elements, inline scripts, extra classes, parsing info from ids, etc).

更新 2: 似乎 HTML 5 data- 属性特性在这里有很多支持(我倾向于同意,它看起来像一个可靠的选择).到目前为止,我还没有看到对这个建议的反驳.使用这种方法是否有任何问题/陷阱需要担心?或者它只是对当前 W3C 规范的无害"失效?

Update 2: It seems that the HTML 5 data- attribute feature has a lot of support here (and I tend to agree, it looks like a solid option). So far I haven't seen much in the way of rebuttals for this suggestion. Are there any issues/pitfalls to worry about using this approach? Or is it simply a 'harmless' invalidation of the current W3C specs?

推荐答案

HTML 5 明确允许以 data 开头的自定义属性.因此,例如,<p data-date-changed="Jan 24 5:23 p.m.">Hello</p> 是有效的.由于它受到标准的正式支持,我认为这是自定义属性的最佳选择.而且它不需要您使用 hack 重载其他属性,因此您的 HTML 可以保持语义.

HTML 5 explicitly allows custom attributes that begin with data. So, for example, <p data-date-changed="Jan 24 5:23 p.m.">Hello</p> is valid. Since it's officially supported by a standard, I think this is the best option for custom attributes. And it doesn't require you to overload other attributes with hacks, so your HTML can stay semantic.

来源:http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes

这篇关于自定义属性 - 是还是不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 16:22