我想将变量“i”放入此代码中:
do {
$('.dot:nth-child(1)').click(function(){
$('.inside').animate({
'width' : (i*width)+'%'
}, 500);
});
i++;
}
while (i <= number);
像这样 - 但它不起作用:
do {
$('.dot:nth-child('+ i +')').click(function(){
$('.inside').animate({
'width' : (i*width)+'%'
}, 500);
});
i++;
}
while (i <= number);
最佳答案
这是经典的闭包问题:传递给 click
的函数具有对 i
变量的持久引用,而不是 >创建函数时的副本。因此,当点击发生时(循环结束后),所有点击
最终都会使用i
的值。
通常的解决方案是使用构建器函数:
do {
$('.dot:nth-child('+ i +')').click(buildHandler(i));
i++;
}
while (i <= number);
function buildHandler(index) {
return function(){
$('.inside').animate({
'width' : (index*width)+'%'
}, 500);
};
}
<小时/>
也就是说,在这种情况下,您不需要为每个元素使用不同的处理函数;相反,只需使用一个处理函数来检查它正在处理哪个子进程:
$('.dot').click(function(){
var index = $(this).index();
$('.inside').animate({
'width' : (index*width)+'%'
}, 500);
});
更多:index
关于Javascript 变量值作为 html 类名中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378993/