1

How do I loop over an Array which has 5 elements. I have 5 elements with ids like imgone, imgtwo, imgthree, imgfour, imgfive.

var ids =
[ 
    "#imgone",
    "#imgtwo",
    "#imgthree",
    "#imgfour",
    "#imgfive"
]; 
for (var i = 0; id = ids[i]; i++)
{  
    $(id).click(function() {

        $("#cell1,#cell2,#cell3,#cell4,#cell5").hide(); 
         $("#cell" + (i+1)).show(); 

    });
}
});

Then I have an 5 a tag elements like

<a href="#"  id="imgone"><img src ="myimage1" /></a>    
<a href="#"  id="imgtwo"><img src ="myimage2" /></a>    
<a href="#"  id="imgthree"><img src ="myimage3" /></a>    
<a href="#"  id="imgfour"><img src ="myimage4" /></a>    
<a href="#"  id="imgfive"><img src ="myimage5" /></a> 

cell1 , cell2, et-al are my blocks that I need to show/hide onclick of a elements.

btw this code always hides all the cell blocks and shows cell6, which does not exist in my code. I mean $("#cell" + (i+1)).show(); never takes values of i as 0, 1 , 2 , 3 or 4.

So how do I iterate over an array and show hide my cells. I think something is wrong with this line of code $(id).click(function() but can't figure out what???

singularity
  • 37
  • 1
  • 4

2 Answers2

3

This is a closure issue, the variable i points to the i used in the loop, and at the time of execution it is always 6.

use this code instead

for (var i = 0; id = ids[i]; i++)
{  
    var fnc = function(j){
        return function() {
            $("#cell1,#cell2,#cell3,#cell4,#cell5").hide(); 
            $("#cell" + (j+1)).show();
        };
    }(i);
    $(id).click(fnc);
}

For more on javascript closures see How do JavaScript closures work?

Community
  • 1
  • 1
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
1

you could jquerify it :

var ids =
[ 
    "#imgone",
    "#imgtwo",
    "#imgthree",
    "#imgfour",
    "#imgfive"
]; 
$(ids.join(,)).each(function(i){
    $(this).click(function(){
        $("#cell1,#cell2,#cell3,#cell4,#cell5").hide(); 
        $("#cell" + (i+1)).show();
    });
});
gion_13
  • 41,171
  • 10
  • 96
  • 108
  • $(this).click(function(){ Control never gets inside this function. and btw what is this function parameter i – singularity Feb 13 '11 at 08:47
  • i is the index of the iterated element. see more at http://api.jquery.com/each/. Why do you say this doesn't work? – gion_13 Feb 13 '11 at 14:38
  • coz it didn't, though it should. Why I am saying control never gets inside this function, coz when I put a simple alert("hi") after $(this).click(function {.... it didnt got executed. have u tried it?? – singularity Feb 13 '11 at 14:57
  • what version of jquery do you use? – gion_13 Feb 13 '11 at 17:44
  • i don't know in witch version of jquery the array-of-selectors selector was introduced ($([selector1,selector2,...selectorn]) ), so you could try using the selectors separated by comma : $(selector1,selector2,..selectorn).see update – gion_13 Feb 13 '11 at 19:23