Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem you have here is that the variable <code>item</code> changes with each loop. When you are referencing <code>item</code> at some later point, the last value it held is used. You can use a technique called a <a href="http://matthew-marksbury.blogspot.com/2008/12/javascript-closures-and-scope.html" rel="noreferrer">closure</a> (essentially a function that returns a function) to quickly scope the variable differently.</p> <pre><code> for (var i in this.items) { var item = this.items[i]; $("#showcasenav").append("&lt;li id=\"showcasebutton_"+item.id+"\"&gt;&lt;img src=\"/images/showcase/icon-"+item.id+".png\" /&gt;&lt;/li&gt;"); $("#showcasebutton_"+item.id).click( // create an anonymous function that will scope "item" (function(item) { // that returns our function return function() { alert(item.id); self.switchto(item.id); }; })(item) // immediately call it with "item" ); } </code></pre> <p>A side note - I see that you have jQuery here. It has a helper function <a href="http://api.jquery.com/jQuery.each" rel="noreferrer"><code>$.each()</code></a> that can be used with arrays, and can be a shortcut for simple for/each loops. Because of the way the scoping works in this call - you wont need to use a closure because "item" is already the parameter of the function when it was called, not stored in a <code>var</code> in the parent function's scope, like was true in your example.</p> <pre><code>$.each(this.items,function(i, item) { $("#showcasenav").append("&lt;li id=\"showcasebutton_"+item.id+"\"&gt;&lt;img src=\"/images/showcase/icon-"+item.id+".png\" /&gt;&lt;/li&gt;"); $("#showcasebutton_"+item.id).click(function() { alert(item.id); self.switchto(item.id); }); }); </code></pre>
 

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