将自己的属性添加到HTML元素可以吗? [英] Is it OK to add your own attributes to HTML elements?

查看:109
本文介绍了将自己的属性添加到HTML元素可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

Custom attributes - Yay or nay?

HTML标签上的非标准属性。好东西?坏事?你的想法?


在我正在学习的当前学习项目中,我需要添加一个属性,其值将是数。起初,我想过使用ID为此目的,但一个答案显示,这样做不好。



如果我创建自己的属性,比如说messid并指定一个数字价值,如12,6等吗?



这就是为什么我想这样做,以便你可以纠正我,如果我做的是完全错误的:
我需要在JavaScript中使用这个数字(使用jQuery)。只需考虑属性的值很容易,但从m12或m6等字符串中提取数值是一件痛苦的事情。 (我是JavaScript世界的初学者。)

解决方案

有很多关于这方面的讨论:



在一天结束时,我认为数据属性是最好的方式去。他们正在HTML5中引入,以避免名称冲突。从本质上讲,如果你想存储任何与你有关的数据,只需在属性名称前添加data-:

 < div class =userdata-userid =5>< / div> 

唯一的缺点就是您的XHTML无法验证,但我诚实地不要不关心那些东西。 (没错,我说了)

Possible Duplicates:
Custom attributes - Yay or nay?
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?

In current learning project I am working on, I need to add an attribute whose value will be a number. At first I thought of using "id" for this purpose but an answer revealed that it is not good to do that.

Is it OK if I create my own attribute, say "messid" and assign a numeric value such as "12", "6" etc to it?

Here is why I want to do this so that you can correct me if I am doing it totally wrong: I need to access this number in my JavaScript (using jQuery). Just taking the value of attribute is easy but extracting the numeric value from a string like "m12" or "m6" is a pain. (I am a beginner in JavaScript world.)

解决方案

There has been much discussion about this:

At the end of the day, I am on the camp that believes data attributes are the best way to go. They are being introducted in HTML5 to avoid name conflicts. Essentially, if you want to store anything data related you just prepend "data-" on the attribute name:

<div class="user" data-userid="5"></div>

The only con to the whole thing is then that your XHTML won't validate, but I honestly don't care about that stuff. (That's right, I said it)

这篇关于将自己的属性添加到HTML元素可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆