Monday, September 9, 2013

how to use jquery .data with dynamically added element

how to use jquery .data with dynamically added element

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 (as opposed to $playerSprite) like so
function Player() {
this.inFight = false;
}
player = new Player();
$playerSprite = $("<img>", {
"id":"test",
"src":
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1RhDvl1GyxgFU3aePV9xVdkYaBVuvrYh1fCD4kyc-nB6zLmXvqOgE2WNagDSwNGNoZGwKR9796ldgg3mxFexKBNcB19SdNeZW5PWWpEJmT_wlswnk10zvd80swXS1q0aZFmmu1SRBJOg/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 in a div, i can access the img
with the 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":
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1RhDvl1GyxgFU3aePV9xVdkYaBVuvrYh1fCD4kyc-nB6zLmXvqOgE2WNagDSwNGNoZGwKR9796ldgg3mxFexKBNcB19SdNeZW5PWWpEJmT_wlswnk10zvd80swXS1q0aZFmmu1SRBJOg/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);
if i click on the img it alerts "success" and then i get Uncaught
TypeError: Cannot read property 'level' of undefined
fiddle.jshell.net/6Erj5/3/show/:40
working fiddle and fiddle with issue

No comments:

Post a Comment