有没有一个很好的方法来附加JavaScript对象到HTML元素? [英] Is there a good way to attach JavaScript objects to HTML elements?

查看:85
本文介绍了有没有一个很好的方法来附加JavaScript对象到HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将JavaScript对象与HTML元素相关联。有没有一个简单的方法呢?



我注意到 HTML DOM 定义了一个setAttribute方法,它看起来像为任意属性名定义的。但是这只能设置字符串值。 (您当然可以使用这个键将密钥存入字典中。)



细节(虽然我对一般问题感兴趣) :



具体来说,我有一个HTML元素表示树中的节点,我正在尝试启用拖放,但是jQuery drop事件只会给我元素被拖放。



将信息传递给事件处理程序的正常模式似乎是在创建JavaScript对象的同时创建HTML元素,然后通过关闭这些JavaScript对象来定义事件处理程序 - 但是在这种情况下这不太好(我可以有一个全局对象在拖动开始时被填充,但这感觉很糟糕)。

你已经看过

解决方案

noreferrer> jQuery data()方法?如果需要,您可以将复杂对象分配给元素,或者您可以至少使用该方法来保存对对象(或其他数据)的引用。


I want to associate a JavaScript object with an HTML element. Is there a simple way to do this?

I noticed HTML DOM defines a setAttribute method and it looks like this is defined for arbitrary attribute name. However this can only set string values. (You can of course use this to store keys into a dictionary.)

Specifics (though I'm mostly interested in the general question):

Specifically, I have HTML elements representing nodes in a tree and I'm trying to enable drag-and-drop, but the jQuery drop event will only give me the elements being dragged and dropped.

The normal pattern for getting information to event handlers seems to be to create the HTML elements at the same time as you are creating JavaScript objects and then to define event handlers by closing over these JavaScript objects - however this doesn't work too well in this case (I could have a global object that gets populated when a drag begins... but this feels slightly nasty).

解决方案

Have you looked at the jQuery data() method? You can assign complex objects to the element if you want or you can leverage that method to hold a reference to an object (or some other data) at the very least.

这篇关于有没有一个很好的方法来附加JavaScript对象到HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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