[Greasemonkey] addEventListener inside loop

Daniel Hood danhood at gmail.com
Wed Feb 1 00:31:07 EST 2006


I'm have a bit of trouble with some code involving looping over some
range and adding event listeners to elements.  It seems that the
variables referenced in the anonymous function being bound to that
event don't have the state of the loop variable at the time of
binding, but rather the value once the loop has completed.  This is a
much simplified case of the problem I am experiencing, but it
illustrates the point.  I believe that this can be solved via a
closure, but I don't seem to be having any luck.

Any help would be appreciated.  Thanks,

--Dan

--GM script--
// ==UserScript==
// @name          Test
// @description   Attempt to understand this behavior
// @include       *test.html
// ==/UserScript==


function do_stuff() {
    for(i = 1; i <= 3; i++) {
        document.getElementById("button" +
i).addEventListener("click", function() { alert(i); }, false);
    }
}

window.addEventListener("load", do_stuff, false);


--HTML--
<html>
  <head>
    <title>Test</title>
  </head>
  <body>
    <input type="button" id="button1" value="button1" /><br />
    <input type="button" id="button2" value="button2" /><br />
    <input type="button" id="button3" value="button3" /><br />
  </body>
</html>


More information about the Greasemonkey mailing list