向DOM节点添加属性是不好的做法吗? [英] Is it bad practice to add properties to DOM nodes?

查看:108
本文介绍了向DOM节点添加属性是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript可以将任意属性和方法添加到任何对象,包括DOM节点。假设属性的名称空间很好(像$ code> _myLib_propertyName ),这样就不太可能产生冲突,有没有什么好的理由不能在DOM节点中隐藏数据? p>

有没有很好的用例这样做?



我想像这样做经常会导致一个马虎的编码风格或代码令人困惑或反直觉,但似乎也有时候将自定义属性放入DOM节点将是一种有效和便利的技术。

解决方案

我认为,不要在DOM中存储数据的最好的理由是因为DOM是为了表示HTML页面的内容结构和样式。虽然您可以确定以节点名称的方式将数据添加到节点中以避免冲突,但您将数据状态引入视觉表示。



我正在尝试在DOM中找到或反对存储数据的示例,并抓住我的头来找到令人信服的案例。过去,我发现数据状态与视觉状态的分离在我重新设计网站的过程中节省了头痛。


JavaScript lets you add arbitrary properties and methods to any object, including DOM nodes. Assuming the property was well namespaced (something like _myLib_propertyName) so that it would be unlikely to create a conflict, are there any good reasons not to stash data in DOM nodes?

Are there any good use cases for doing so?

I imagine doing this frequently could contribute to a sloppy coding style or code that is confusing or counter-intuitive, but it seems like there would also be times when tucking "custom" properties into DOM nodes would be an effective and expedient technique.

解决方案

I think more than anything, the best reason not to store data in the DOM is because the DOM is meant to represent content structure and styling for an HTML page. While you could surely add data to the nodes in a well-namespaced manner as to avoid conflicts, you're introducing data state into the visual representation.

I'm trying to find an example for or against storing data in the DOM, and scratching my head to find a convincing case. In the past, I've found that the separation of the data state from the visual state has saved headache during re-designs of sites I've worked on.

这篇关于向DOM节点添加属性是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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