[英]Looping over Array Elements By Calling them by Id
How do I loop over an Array which has 5 elements. 如何遍历具有5个元素的数组。 I have 5 elements with ids like imgone, imgtwo, imgthree, imgfour, imgfive. 我有5个元素,如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 然后我有一个5个标签元素
<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. cell1,cell2,et-al是我的块,我需要显示/隐藏元素的onclick。
btw this code always hides all the cell blocks and shows cell6, which does not exist in my code. 顺便说一句,这段代码总是隐藏所有的单元格块,并显示我的代码中不存在的cell6。 I mean $("#cell" + (i+1)).show();
我的意思是$("#cell" + (i+1)).show();
never takes values of i as 0, 1 , 2 , 3 or 4. 永远不会将i的值取为0,1,2,3或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??? 我认为这行代码$(id).click(function()
但是无法弄清楚是什么?
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
. 这是一个闭包问题,变量i
指向循环中使用的i
,并且在执行时它始终为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? 有关javascript闭包的更多信息,请参阅JavaScript闭包如何工作?
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();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.