向 DOM 元素添加变量
我想问,向文档正文元素添加自定义变量是否“合法”。 例如:
document.getElementById('elem1').customVariable = 'xxx';
此代码可以正常工作,但我不知道它是否“允许”
它不会出现在标签参数列表中,但变量可以在进一步的代码中使用。
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..
我认为这会起作用,但添加自定义属性的更常见方法是这样的:
然后
或者如果旧浏览器在
setAttribute
上阻塞编辑
感谢 pimvdb 指出这一点你也可以这样做,
但请注意,你必须注意你如何命名它——骆驼外壳可能会把它弄掉。你会想要
I think that will work, but the more common way to add custom attribute is like this:
And then
Or if older browser choke on
setAttribute
EDIT
Thanks to pimvdb for pointing out that you can also do
Just note that you'll have to watch how you name this -- the camel casing can throw it off. You'll want