Reputation: 115
I have a number of thumbnails on my website, that are supposed to all bring up the same slide show, but with different slides displayed (by adding and removing a .hidden
class). This will be done by function showWork(toShow)
, with toShow
being a number referring to the slide that is supposed to be visible. The function also alerts back this parameter.
I further want to do this with JavaScript by binding mouseup
events to the different thumbnail divs.
As I don't want to list every bind separately, I decided to put all the div ids in an array (workArr
) and create a for-loop:
for(i=0; i < workArr.length; i++){
$("#"+workArr[i]).bind({
mouseup: function(){
showWork(i);
}
});
}
My array has a length of 14. When I run this code, I get an alert of "14", and no slide displayed (as there is no 14. slide).
What am I doing wrong?
Upvotes: 2
Views: 105
Reputation: 22943
You need to use closure:
for(i=0; i < workArr.length; i++){
(function(i){
$("#"+workArr[i]).bind({
mouseup: function(){
showWork(i);
}
});
})(i);
}
Upvotes: 4