[Greasemonkey] addEventListener inside loop
Arvid Jakobsson
arvid.jakobsson at gmail.com
Wed Feb 1 11:05:05 EST 2006
2006/2/1, Daniel Hood <danhood at gmail.com>:
> 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>
> _______________________________________________
> Greasemonkey mailing list
> Greasemonkey at mozdev.org
> http://mozdev.org/mailman/listinfo/greasemonkey
>
This is how i would do it, but i can't say if it's a good way or not:
function foo(i) {
return function () {
alert(i);
}
}
function do_stuff() {
for(i = 1; i <= 3; i++) {
var button = document.getElementById("button" + i);
button.addEventListener("click", foo(i), false);
}
}
More information about the Greasemonkey
mailing list