[英]Adding variables to DOM elements
I would like to ask, if is 'legal' to add custom variables to document body elements. 我想问一下,如果将“自定义变量”添加到文档正文元素是“合法的”。 For example: 例如:
document.getElementById('elem1').customVariable = 'xxx';
This code just work, but i don't know if it is 'allowed' 这段代码正常工作,但我不知道它是否“允许”
It doesn't appear in list of tag's arguments, but variable is usable in further code.. 它不会出现在标记参数列表中,但变量可用于更多代码中。
I think that will work, but the more common way to add custom attribute is like this: 我认为这会有效,但更常见的添加自定义属性的方法是这样的:
<div id="elem1" data-customVariable="foo"
And then 然后
document.getElementById('elem1').setAttribute("data-customVariable", "bar");
Or if older browser choke on setAttribute
或者如果旧的浏览器在setAttribute
阻塞
document.getElementById('elem1')["data-customVariable"] ="bar";
EDIT 编辑
Thanks to pimvdb for pointing out that you can also do 感谢pimvdb指出你也可以做到
document.getElementById('elem1').dataset.customVariable ="bar";
Just note that you'll have to watch how you name this -- the camel casing can throw it off. 请注意,你必须注意你的名字 - 骆驼外壳可以把它扔掉。 You'll want 你想要的
<div id="elem1" data-custom-variable="xxx"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.