admin管理员组文章数量:1339455
Is this wrong? If so why?
var elm = document.getElementById("myElm");
elm.customValue = {attr1 : "test", attr2 : "test"};
I understand how to use the data attributes, but I don't want to muddy up my dom with all those attributes.
Is this wrong? If so why?
var elm = document.getElementById("myElm");
elm.customValue = {attr1 : "test", attr2 : "test"};
I understand how to use the data attributes, but I don't want to muddy up my dom with all those attributes.
Share Improve this question asked Feb 11, 2012 at 16:49 Phillip BurchPhillip Burch 4595 silver badges11 bronze badges 1- Possible duplicate of Can I add arbitrary properties to DOM objects? – RiZKiT Commented Jun 4, 2019 at 7:50
3 Answers
Reset to default 10This introduces a memory leak in some browsers because you bind a native C object (the DOM element) and a JS object together and some garbage collection algorithms cannot deal with this. IE is one of them.
Here is an MSDN article about IE memory leaks: http://msdn.microsoft./en-us/library/ie/bb250448(v=vs.85).aspx
Bottom line, why wouldn't you use the proper tools available? You have no idea if in the future, near or far, whatever custom property name you are using will be added to the w3c specifications for that particular element. Now, suddenly your code is broken.
Never mind that adding custom properties to elements which already have defined properties makes your code a maintenance nightmare. Whether it's you or someone else maintaining it in the future, there's going to be a "wtf" moment where the developer is trying to igure out if a) a custom property was added to the element or b) the element itself is in fact a custom object.
Finally, what if that element is replaced in the dom via Ajax or dynamic HTML? Now the property is gone and your code is broken.
You should consider HTML5 data-attributes.
From the man himself: http://ejohn/blog/html-5-data-attributes/
本文标签: javascriptStoring custom data in dom elementsStack Overflow
版权声明:本文标题:javascript - Storing custom data in dom elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743580811a2505701.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论