我有3 .a和一个函数,它应该警告数字[0,1或2] .a属于mouseover-ed时:
?function a(){
for(var c=0; c<3; c++){
alert(c);
$('.a:eq('+c+')').mouseover(function(){alert(c)});
}
}
Run Code Online (Sandbox Code Playgroud)
当我执行它时,第一个alert(c)被触发三次,消息分别为"0","1","2",如预期的那样.
然而,当mouseover .a,无论哪个.a它是,它提醒"3".
如果有人能解释为什么会发生这种情况并提供解决方案,我将不胜感激.
因为c = 3.
你的循环C每次运行时都会增加1,C在代码运行后仍然等于3,为你的警报提供值C3,即3.
您的示例可以完全重写并简化为
$('.a').mouseover(function(){
alert($(this).index());
});
Run Code Online (Sandbox Code Playgroud)
这将为具有类的所有元素生成警报a,并在$('.a')生成的数组中给出它们的位置.
BTW:将函数放入循环时出现JSLint错误,如果你想让JSLint保持高兴请查看这个问题