JS Image Gallery Loop

    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 warning always shows 18. this is the number of thumbnail images. I want it to show which thumbnail I clicked. why doesn't he show it? also i need to pass this value of the clicked thumbnail forward to another function so that i can also display the subsequent full image. can anyone help?

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

0


a source to share


1 answer


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

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

      



Explanation:

In variable I iterate over the code I have a global variable for the internal anonymous functions that you produce for the event handler, but you should notice that while it seems that you are creating another anonymous function, they all look at i, which is in a more global scope. and he's still the same me for all of them. So the last value will be warned, to avoid this, I created another wrapper function for yours to wrap the value i in a different scope, so a different warning will be displayed for the other element. The explanation in the comments is also correct, I advise your google to close Javascript and read some articles about it once you realized that it can become a very powerful piece of hardware.

0


a source







All Articles