开发者

Looping over Array Elements By Calling them by Id

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="i开发者_JS百科mgthree"><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???


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?


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();
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜