jQuery - 如何将 DOM 元素和 Javascript 对象链接在一起?
我希望能够将 javascript 对象与 dom 元素链接起来,但找不到正确完成此操作的方法。举个例子:假设打开一个包含库存的页面时,它会加载其中包含的所有项目,当我将鼠标悬停在其中的图像上时,会创建一个包含一些信息的小工具提示。页面上会有很多这样的项目,我希望能够将 DOM 元素与一个对象链接起来,这样我就可以轻松访问它的属性。我希望我能正确地解释我自己。
说我在库存中有这个:
<div id="slot1"><img id="item1"></div>
<div id="slot2"><img id="item2"></div>
并说我有一个名为 slot1 和 slot2 的 javascript 对象:
对象 slot1 具有需要在工具提示中显示的所有属性,所以我想在鼠标悬停事件中执行类似的操作:
this.showTooltip()
any如果我需要更好地解释,请说出来,帮助会很大!
- 泰国蝎子
I want to be able to link a javascript object with a dom element but cant find a way for this to be done properly. An example: say when opening a page with an inventory it loads all the items contained in it and when I hover over the images inside it creates a small tooltip with some information. Well there will be much of these items on the page and i want to be able to link the DOM element with an object so i can access its properties easily. I hope im explaining my self properly.
say I had this inside an inventory:
<div id="slot1"><img id="item1"></div>
<div id="slot2"><img id="item2"></div>
and say i have a javascript object called slot1 and slot2:
the object slot1 has all the properties that need to be shown in the tooltip so i would like to do something like this in the mouseover event:
this.showTooltip()
any help would be great ty if i need to explain it better just say!
-Thaiscorpion
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用jQuery data:
显然,在注册这个事件之前,你必须将对象分配给每个DOM带有
$(selector).data(key, value)
的元素。这些示例期望每个应该有工具提示的 DOM 元素都有一个名为
.hasToolTip
的类。有关
.data()
函数的更多信息,请参阅 jQuery 文档 。Use jQuery data:
Obviously, before you can register this event, you have to assign the object to every DOM element with
$(selector).data(key, value)
.These example expects that every DOM element which should have a tooltip has a class named
.hasToolTip
.Look at the jQuery documentation for more information about the
.data()
function.只需让 javascript 对象知道它正在监视的对象的 ID 即可。
然后:
slot1.showTooltip();
或者更好的是,不要传入 ID,而是传入对象:
var slot1 = new Tooltipper($('#slot1'));
这样你就不必每次都进行 DOM 查找。
Just have the javascript object know the ID of the object it's watching.
And then:
slot1.showTooltip();
Or better yet, instead of passing in the ID, pass in the object:
var slot1 = new Tooltipper($('#slot1'));
This way you don't have to do a DOM lookup each time.