cómo usar jquery .data con un elemento agregado dinámicamente

i am making a game in which i have a "player", the player is a image with jquery data attached, i am able to access the data when i name the img $playerSprite even when using the id (Opuesto a $playerSprite) al igual que

function Player() {
    this.inFight = false;
}

player = new Player();
$playerSprite = $("<img>", {
    "id":"test",
    "src": "http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png",
}).data("model", player);

$("div").append($playerSprite);

alert($("#test").data("model").inFight);

however when i create the "player" as a img en un parche de div, i can access the img con el id however i cant access the data with it. with the below code

function Player() {
    this.level = 1;
}

function Game() {
    var player = new Player();
         $("div").html($("<img>", {
            "class": "onTop displayCurrentHealth",
                "src": "http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png",
                "alt": "you",
                "id": "test"
        }).data("model", player)
        );
}
Game();
$("#test").click(function(){alert("success");});
$("#test").click(function(){alert($(this).data("model").level);});
alert($("#test").data("model").level);

si hago clic en el img it alerts "success" and then i get Uncaught TypeError: Cannot read property 'level' of undefined fiddle.jshell.net/6Erj5/3/show/:40

violín de trabajo y fiddle with issue

preguntado el 09 de septiembre de 13 a las 23:09

try $("#test").on('click',function(){alert($(this).data("model").level); -

@Raghu thats not the issue i said already that id does alert "success", (if it works please provide a fiddle, because it must mean something other then i think your saying) -

2 Respuestas

It is because you are creating two elements on the page with the same id, #test. The first is the static div, then you are adding a child img to it with an id also of test. Invalid html, the jQuery will only find the first test (the div) and you didn't add the data to the div. Change the id of the image, or get the child img of the div eg

$('#test').find('img').data('model')

Respondido el 09 de Septiembre de 13 a las 23:09

you are right i fixed it (jsfiddle.net/6Erj5/5) it was just a example so i didnt pay attention, thnx im not sure if thats the same problem of my actual game, will be back if i got more issues with this, thnx again. - Enfriador de matemáticas

ok found my error (in the game) - real stupid like most errors. i didnt change from the old syntax (objname[prop]) a lo nuevo $("#player").data("stats")[prop] wow! humans are dumb! but we learn - Enfriador de matemáticas

I'm intrigued as to what game you are writing. Is it available to be looked at online. I just recently finished writing a Game (Snakes and ladders board game), did exactly the same thing you did with a player object which had an img, but I never used any data on the actual HTML element, I stored a reference to the img tag on the actual player object, I never liked to put extra data in the DOM. I got canvas and webGL involved too, I would be interested in having a look at your code, if your willing - Ojay

lol its a game im making to learn atm but feel free to check it out (you can find it with the link in my profile as well) borisute.com/geshem/2013/mkeller/adventure.html not very exiting (my model for the concepts is from runescape) atm im still using my old script until my new one is fully updated (adventure.js instead of adventuretest.js) and i keep switching to test the new one. - Enfriador de matemáticas

yep minesweeper has only like 3 lines of jquery but it works, if you look at the code you can see i started making it editable, (size and bombs) but then lost interest. - Enfriador de matemáticas

The problem is that in this event handler:

$("#test").click(function () {
    alert($(this).data("model").level);
});

this significa #test which doesn't have any data set to is.
Si lo cambia así, debería funcionar:

$("img").click(function () {
    alert($(this).data("model").level);
});

About your question regarding dynamically added elements: please read about event delegation in javascript. Quick example:

$(existingParentElement).on('eventType', 'dynamicElement', eventHandler);

En tu caso:

$('#test').on('click', 'img', function () {
    alert($(this).data("model").level);
});

Respondido el 09 de Septiembre de 13 a las 23:09

you didnt really address the case, just the question, and the crucial point is that there are two elements with id of test, not very helpful, anyway i already got a good answer. keep trying. - Enfriador de matemáticas

Yeah, I glanced over the duplicated ids, but still, this is the way to handle events for dynamically added elements. I woudn't say it's not helpful. :P - Sudee

not helpful for this question, i know how to add events to dynamically added elements, and as i pointed out the first onclick obras. - Enfriador de matemáticas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.