我的调试技巧并没有帮助我弄清楚我在这里做错了什么。
我希望使用setTimeout函数在指定时间后为数组中的每个元素设置动画。
我没有收到任何错误,并且循环似乎运行得很好,但是,阵列中没有任何元素最终从原始位置移动到新位置。
function publicity()
{
// placing elements with class name 'cCameras' inside an array
var eCamerasArray = $(".cCameras").toArray();
// creating 2 arrays to hold left & top values of each element
var iLeftPosArray = [];
var iTopPosArray = [];
// loop to run through each element in array
for( var i = 0; i < eCamerasArray.length; i++)
{
// timer variable set for each element to be used in setTimeout func.
var timer = Math.floor (Math.random()*300) + 100;
// setTimeout func. used to animate each element after a specified (timer) time
window.setTimeout (function ()
{
iLeftPosArray[i] = Math.floor (Math.random() *139) + 360;
iTopPosArray[i] = Math.floor (Math.random() *160) + 100 ;
$(eCamerasArray[i]).animate ({left: iLeftPosArray[i] + "px", top: iTopPosArray[i] + "px"}, 100, "linear");
return [iLeftPosArray[i], iTopPosArray[i]];
}, timer);
}
}
答案 0 :(得分:1)
你可以通过创建闭包来修复它:
(function publicity() {
var eCamerasArray = $(".cCameras"),
iLeftPosArray = [],
iTopPosArray = [],
timer;
for(var i = 0; i < eCamerasArray.length; i += 1) {
timer = Math.floor (Math.random() * 300) + 100;
(function (i) {
window.setTimeout (function () {
iLeftPosArray[i] = Math.floor (Math.random() * 139) + 360;
iTopPosArray[i] = Math.floor (Math.random() * 160) + 100 ;
$(eCamerasArray[i]).animate ({left: iLeftPosArray[i] + "px", top: iTopPosArray[i] + "px"}, 300, "linear");
return [iLeftPosArray[i], iTopPosArray[i]];
}, timer);
}(i));
}
}());
您可以在此处查看效果:http://jsfiddle.net/zHUAt/2/
祝你好运!
答案 1 :(得分:1)
展开一个简单的循环,你可以看到会发生什么:
var i = 0;
window.setTimeout( function(){
//No local i so it must be outside
console.log(i);
}, 1000 );
i++;
window.setTimeout( function(){
//No local i so it must be outside
console.log(i);
}, 1000 );
i++;
window.setTimeout( function(){
//No local i so it must be outside
console.log(i);
}, 1000 );
如您所见,所有函数都引用相同的i
,所以
一旦定时器触发,它们都会记录2
。他们都不是
拥有本地i
。
您可以像这样创建“本地”i
:
(function(i){
|---------^ //i found here, no need to use the global i
| window.setTimeout( function(){
-------------------- //no local i here so it must be outside
console.log(i);
}, 1000 );
})(i) //pass the "global" i as argument, with the value it has right now