2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
max
  • 115
  • 1
  • 9
  • That's one mistake every newbie js developer makes !! – Clyde Lobo Jun 30 '12 at 16:00
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Ja͢ck Jun 30 '12 at 16:01
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Brian Tompsett - 汤莱恩 May 27 '21 at 18:42

1 Answers1

4

You need to use closure:

for(i=0; i < workArr.length; i++){
    (function(i){
        $("#"+workArr[i]).bind({
            mouseup: function(){
                showWork(i);
            }       
        });        
    })(i);
}
bjornd
  • 22,397
  • 4
  • 57
  • 73