开发者

jQuery - How to link together a DOM element and a Javascript object?

开发者 https://www.devze.com 2023-03-20 13:49 出处:网络
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 contain

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开发者_StackOverflow社区.

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


Use jQuery data:

$("div.hasToolTip").hover(
   function() {
       //Get the associated data with the DOM element
       //with $(this).data(someKey)

       showToolTip($(this).data('toolTipInformation'));
   },
   function() {
       //Here you can hide all tooltips
   }
);

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.


Just have the javascript object know the ID of the object it's watching.

function Tooltipper(divID) {
    this.id = divID;
}

Tooltipper.prototype.showTooltip = function () {
    // do tooltip stuff
    $('#' + this.id).tooltip(); // assuming that it has a tooltip thing
};

var slot1 = new Tooltipper('slot1'),
    slot2 = new Tooltipper('slot2');

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消