有没有一个很好的方法来附加JavaScript对象到HTML元素?

编程入门 行业动态 更新时间:2024-10-16 00:19:58
本文介绍了有没有一个很好的方法来附加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元素?

本文发布于:2023-11-23 18:51:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622511.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:很好   方法来   元素   对象   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!