Refer to old iterator values ​​in click () function for javascript / jQuery (closing issue)

I am trying to get the "click ()" function to display the value of 'i' at the time the function is passed. But back to the value of 'i' after its completion. I draw a space on how to make a function refer to the value of 'i' when I first passed the function.

 for( var i=0; i<10; i++){ var ts = $('#<span></span>').clone().click(function(){ alert(i); }); } 

Note:

'#' should not be, nor should '.clone()'

+4
source share
2 answers

Something like this will work:

 for(var i=0; i<10; i++){ (function(j) { var ts = $('<span></span>').click(function(){ alert(j); }); })(i); } 

You can try it here . Although your creation doesn't work a bit, I'm not sure why you want to create a new element in order to clone it, and there is still # . I deleted both of them above, but this does not affect the solution to the internal function.

+4
source

You need to move the body of the loop into a separate function that takes i as a parameter.

You can use a regular function, for example:

 for(var i=0; i<10; i++) { makeCopy(i); } function makeCopy(i) { var ts = $('#<span></span>').clone().click(function(){ alert(i); }); } 

You can also use the built-in method, for example: (beware of confusing syntax)

 for(var i=0; i<10; i++) { (function(i) { //Note i parameter var ts = $('#<span></span>').clone().click(function(){ alert(i); }); ... })(i); //Note i parameter } 
+2
source

All Articles