The variable myCollection holds jQuery DOM elements, and I want to set a callback function for each of their onclick event as shows below. Actually what I want is, to incrementally set or could say “burn” the number for each element, so when they are getting clicked, its own number would get alerted. This code alerts the last value of number when it was incremented in the loop the last time.
var number = 1;
myCollection.each(function(){
this.onclick = function() { someFunction(number) };
number++;
});
//This function is somewhere else, but accessible.
function someFunction(number) {
alert(number);
}
How can I copy or instantiate callback functions for each elements, so they would have the same process but with different arguments bind to them?
A classic scoping problem, it can be solved like this:
Note that jQuery already includes a correctly scoped index inside the each callback, so all you need to do is: