Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to use jquery .data with dynamically added element
    primarykey
    data
    text
    <p>i am making a game in which i have a "player", the player is a image with jquery <code>data</code> attached, i am able to access the <code>data</code> when i name the <code>img</code> <code>$playerSprite</code> <strong>even when using the id</strong> (as opposed to <code>$playerSprite</code>) like so</p> <pre><code>function Player() { this.inFight = false; } player = new Player(); $playerSprite = $("&lt;img&gt;", { "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); </code></pre> <p>however when i create the "player" as a <code>img</code> in a <code>div</code>, i can access the <code>img</code> with the <code>id</code> however i cant access the <code>data</code> with it. with the below code</p> <pre><code>function Player() { this.level = 1; } function Game() { var player = new Player(); $("div").html($("&lt;img&gt;", { "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); </code></pre> <p>if i click on the <code>img</code> it alerts "success" and then i get <code>Uncaught TypeError: Cannot read property 'level' of undefined fiddle.jshell.net/6Erj5/3/show/:40</code></p> <p><a href="http://jsfiddle.net/akF2v/6/" rel="nofollow">working fiddle</a> and <a href="http://jsfiddle.net/6Erj5/3/" rel="nofollow">fiddle with issue</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload