javascript 将自定义属性附加到 DOM 节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3363463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append custom attributes to a DOM node
提问by Konrad
Possible Duplicate:
Can I just make up attributes on my HTML tags?
可能的重复:
我可以在我的 HTML 标签上编写属性吗?
Hi,
你好,
I am not sure if what I am asking is even possible, but I'd like to be able to add a custom (nonrendered) propery to an existing HTML DOM node.
我不确定我的要求是否可行,但我希望能够向现有 HTML DOM 节点添加自定义(非渲染)属性。
For example, if I have a simple DOM as below:
例如,如果我有一个简单的 DOM,如下所示:
<body>
<p>
<span id="aSpan"></span>
</p>
</body>
.. I'd like to be able to add a custom property to the span 'aSpan' to store a numeric variable.
.. 我希望能够将自定义属性添加到跨度“aSpan”以存储数字变量。
Is this possible and if so, what is the best way to do it?
这是可能的,如果可以,最好的方法是什么?
Thanks,
谢谢,
回答by Rob
Sure, I do this all the time. You can do it in the html:
当然,我一直这样做。您可以在 html 中执行此操作:
<span id="aSpan" attname="attvalue">
<span id="aSpan" attname="attvalue">
(validators don't like this though, technically it's not valid html but it works)
(虽然验证器不喜欢这个,从技术上讲它不是有效的 html 但它可以工作)
Or via javascript:
或者通过javascript:
element.setAttribute('attname', 'attvalue');
element.setAttribute('attname', 'attvalue');
You can read it with:
您可以通过以下方式阅读:
element.getAttribute('attname');
element.getAttribute('attname');
回答by Nathan Taylor
Take a look at the duplicate questionfor reasons why not to do this this and restrictions on how it can be done legally in HTML 5.
查看重复的问题,了解为什么不这样做的原因以及如何在 HTML 5 中合法完成的限制。
Despite the validation errors you'll receive, using jQuery you can make use of the $.attr()function:
尽管您会收到验证错误,但使用 jQuery 您可以使用该$.attr()函数:
$('.element').attr('foo', 'bar')
回答by fearofawhackplanet
I'm not sure in plain Javascript, but jQuery has the data function.
我不确定是否使用纯 Javascript,但 jQuery 具有数据功能。
$('#aSpan').data('foo', 69);
alert($('#aSpan').data('foo'));
回答by Paper-bat
a simple way.. if your page is dinamic.. you can simply add a value to your ID
一个简单的方法.. 如果你的页面是动态的.. 你可以简单地为你的 ID 添加一个值
a little example if I understand well, you can use it in a class, supposed we have a 56 has ID
一个小例子,如果我理解得很好,你可以在课堂上使用它,假设我们有一个 56 的 ID
<body>
<p>
<span id="aSpan" class="A54F23345A56A23524234"></span>
</p>
</body>
I do simply made a string the ID 'A54F23345A' + 56 + 'A23524234'
我只是做了一个字符串 ID 'A54F23345A' + 56 + 'A23524234'
But you can use it has you wish.. and the id is hidden from users.. you can use more secure script.. but if isn't a security issue.. it works like a charm ^^
但是您可以随心所欲地使用它.. 并且该 ID 对用户是隐藏的.. 您可以使用更安全的脚本.. 但如果不是安全问题.. 它就像一个魅力^^
Have a nice day
祝你今天过得愉快

