Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is one of the tricky things about closure. You are creating those event handlers with a closure over <code>entry</code>. They all have access to that variable, that exact variable. Consequently once those events fire they get only the last value set to entry. You need to break the closure. Here is one way.</p> <pre><code>function addClickHandlers() { var entries = [{id: 1},{id: 2},{id: 3}]; var i = entries.length; while (i--) { var entry = entries[i]; document.getElementById(entry.id).onclick = getClickHandler(entry); } } function getClickHandler(entry) { return function() { console.log("this.id: " + this.id); console.log("entry.id: " + entry.id); }; } </code></pre> <p>Note: I changed your for loop into a while just because it's the fastest way to loop in javascript when order isn't important and I think it's slick.</p> <h2>Added for completeness</h2> <p>There are some other methods designed to deal with this situation. I find that I use them all the time. </p> <p>In Ext there is <code>createDelegate</code></p> <pre><code>myhandler.createDelegate(scope, [arguments], [appendArgs]); </code></pre> <p>For javascript 1.8.5 there is Function.prototype.bind</p> <pre><code>myhandler.bind(scope, arguments) </code></pre> <p>Writing Function.prototype.bind is pretty easy (<a href="http://dhtmlkitchen.com/?category=/JavaScript/&amp;date=2008/09/11/&amp;entry=Function-prototype-bind" rel="nofollow">lifted from here</a>)</p> <pre><code>Function.prototype.bind = function(self, var_args) { var thisFunc = this; var leftArgs = Array.slice(arguments, 1); return function(var_args) { var args = leftArgs.concat(Array.slice(arguments, 0)); return thisFunc.apply(self, args); }; }; </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