0

I have a simple problem in passing variables from one function to a Jquery handle function. In the first function I have a for loop going over a list of items. the function inserts a picture and I want to append a onclick() Jquery handle to the image. The onclick() calls a function that passes the indx of the for loop. Instead of having the value passed the reference is passed so all the onclick handles end up with the same value (the last value of the for loop). the code is as follows:

function setAlbums()

    {
        for(var indx=0;indx<$("li.mainSpPic").length;indx++)
            {
             ....
             $("li.mainSpPic").eq(indx).children("img").eq(0).click(**function(){chngAlbm(indx,albmStrB[1]**);}) ;

    }

So can someone advise how to pass the indx variable that each onclick() function would have a unique value ?

Ari
  • 405
  • 1
  • 4
  • 4

1 Answers1

0

This is because of closure in Javascript. It fails because the handler functions are bound to the variable indx, not the value of the variable indx at the time the function was made. The handler function runs when the for statement has finished.

The solution for this problems is this.

function setAlbums()
{
    for(var indx=0;indx<$("li.mainSpPic").length;indx++)
    {
         ....
         $("li.mainSpPic").eq(indx).children("img").eq(0).click(function(value) {
                return function() {
                  chngAlbm(value,albmStrB[1]);
                } 
         })(indx) ;
     }
}
Rodrigo Villalba Zayas
  • 5,326
  • 2
  • 23
  • 36