tags:

views:

87

answers:

1
 var thumbs = document.getElementsByTagName("img");
 for (var i=0; i<thumbs.length; i++)
 {
  Core.addEventListener(thumbs[i], "click",  function() {alert(i);});
 }

In the above code, the alert always shows18. that is the number of image thumbnails. i want it to show which thumbnail i clicked. why isnt it showing that? also i need to pass that value of the clicked thumbnail forward to another function so that i can display the subsequent full image too. can anyone pls help?

also if there is any better way to do this, pls suggest. thanks a lot in advance.

A: 

This is because the inner anonymous function closes the variable i, therefore it will show you always the last value of iteration. You do next:

Core.addEventListener(thumbs[i], "click",  (function( j) 
                                           { 
                                               return function() 
                                                      {
                                                         alert(j);
                                                      };
                                            })(i));

Explanation:

In you code iteration variable i is kind of global variable for inner anonymous functions which you produce for event handler, but you have to note that although seems like you creating different anonymous function, all of them are looking at i which in more global scope and it is still the same i for all of them. So the last value will be alerted, in order to avoid it I created another wrapper function for yours in order to enclose the value of i within another scope so for different element will see different alert. The explanation in comments is also correct, I advice your to google for Javascript closure and read some articles about it, once you got an idea it might became very powerful equipment.

Artem Barger
this worked. can u pls explain what the above code does?
amit
It wraps a "closure" around the function. It defines an anonymous function which "closes" the variable j (so it wont change) - this function returns a function (your event handler 'alert'). This anonymous function is then called with (i) as an argument so j==i at time of execution.
gnarf
Yeap, the explanation above is very detailed.
Artem Barger