是否有一种将 JavaScript 对象附加到 HTML 元素的好方法? [英] Is there a good way to attach JavaScript objects to HTML elements?

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

问题描述

我想将一个 JavaScript 对象与一个 HTML 元素相关联.有没有简单的方法可以做到这一点?

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

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

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):

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

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.

向事件处理程序获取信息的正常模式似乎是在创建 JavaScript 对象的同时创建 HTML 元素,然后通过关闭这些 JavaScript 对象来定义事件处理程序 - 但是这也不起作用在这种情况下(我可以有一个在拖动开始时填充的全局对象......但这感觉有点讨厌).

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).

推荐答案

你看过 jQuerydata() 方法?如果需要,您可以将复杂对象分配给元素,或者您可以利用该方法至少保存对对象(或其他一些数据)的引用.

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天全站免登陆