Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将数组传递给tweenjs-won';行不通_Javascript_Closures_Tween.js - Fatal编程技术网

Javascript 将数组传递给tweenjs-won';行不通

Javascript 将数组传递给tweenjs-won';行不通,javascript,closures,tween.js,Javascript,Closures,Tween.js,我想用tween.js设置多个屏幕对象的动画 对象被组织在一个数组中,我想将每个单独的元素传递给tween函数,该函数大致如下所示: var target1=document.getElementById('target1'); var target2=document.getElementById('target2'); 目标。推送(目标1); 目标。推送(目标2); 对于(变量i=0;i

我想用tween.js设置多个屏幕对象的动画

对象被组织在一个数组中,我想将每个单独的元素传递给tween函数,该函数大致如下所示:

var target1=document.getElementById('target1');
var target2=document.getElementById('target2');
目标。推送(目标1);
目标。推送(目标2);
对于(变量i=0;i<2;i++){
var tween=new tween.tween(目标[i].dataset)//第i个元素
.至({旋转:360,y:300},750)
.easing(TWEEN.easing.Cubic.InOut)
.onUpdate(函数(){
updateBox(目标[i],本);
})
.start();
}
当我在本地运行代码时,firefox告诉我“box未定义”-这对应于updateBox中的第1行(…)


我想这可能与函数的闭包有关,但我不是JavaScript方面的专家-有人知道吗?

尝试按如下方式重写代码,以避免循环变量的闭包绑定:

var tween = new TWEEN.Tween( targets[i].dataset )  // i'th element
    .to( { rotation: 360, y: 300 }, 750 )
    .easing( TWEEN.Easing.Cubic.InOut )
    .onUpdate( (function(id, ctx) { 
        return updateBox(targets[id], ctx); 
    })(i, this) )
    .start();
更新:
onUpdate
应该接收一个函数作为参数,我错过了。尝试如下:

...
.onUpdate( (function(id, ctx) { 
        return function() { updateBox(targets[id], ctx) }; 
    })(i, this) )
...
更新2:
不应传递给更新,请尝试以下操作:

var tween = new TWEEN.Tween( targets[i].dataset )  // i'th element
              .to( { rotation: 360, y: 300 }, 750 )
              .repeat(Infinity)
              .easing( TWEEN.Easing.Cubic.InOut )
              .onUpdate( (function(id) { 
                return function () { updateBox(targets[id], this); };
              })(i) )
              .start();

注意:在.zip中,您没有在Tween构造函数中使用targets[i].dataset,请注意,

也没有这样做-现在ff抱怨Tween.js中的“TypeError:t未定义”。(最后的第二个分号需要删除)那么现在什么不起作用呢?我不能让你的JSFIDLE工作,TWEEN是未定义的,所以我只是在猜测,会有什么问题。@MikeDooley请尝试新版本。是的,正是我需要的-非常感谢你的时间。我非常感激!
var tween = new TWEEN.Tween( targets[i].dataset )  // i'th element
              .to( { rotation: 360, y: 300 }, 750 )
              .repeat(Infinity)
              .easing( TWEEN.Easing.Cubic.InOut )
              .onUpdate( (function(id) { 
                return function () { updateBox(targets[id], this); };
              })(i) )
              .start();