我注意到 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元素?
发布评论