jQuery .fadeIn()和.fadeOut()在将代码重写为递归回调后,回调工作不按预期工作

重写的代码应显示任意数量的图片,旧代码是静态的。 但是新代码的作用是立即显示arrays的最后一个图像以及所有图像的完全延迟,因此30秒。

我的旧代码看起来像这样,并且与jquery回调一起运行良好。 http://pastebin.com/XH2aRqBh

重写的代码:

//Class Trial Trial = (function() { function Trial(imageArray) { this.images = imageArray; } Trial.prototype.startTrial = function() { $("#noise").hide(0, this.showImages(this.images)); }; Trial.prototype.showImages = function(imageArray) { imageToShow = imageArray.pop(); if(imageToShow === undefined){ $("#noise").show(0); console.log("show noise"); return; } console.log("pop image : ", imageToShow.image.src, " delay : ", imageToShow.delay); $("#img").show(); $("#img").attr("src", imageToShow.image.src); $("#img").fadeIn(0).delay(imageToShow.delay).fadeOut(0, this.showImages(imageArray)); }; return Trial; })(); //create objects and run a Trial image0 = new AMPImage("img/image0.jpg", 10000); image1 = new AMPImage("img/image1.jpg", 500); image2 = new AMPImage("img/image2.jpg", 100); image3 = new AMPImage("img/image3.jpg", 10); image4 = new AMPImage("img/image4.jpg", 500); image5 = new AMPImage("img/image5.jpg", 100); image6 = new AMPImage("img/image6.jpg", 10000); myImageArray = [image6, image5, image4, image3, image2, image1, image0]; trial1 = new Trial(myImageArray); trial1.startTrial(myImageArray); 

和HTML文件

     

JavaScript控制台输出:

 pop image : file:/// ... /img/image0.jpg delay : 10000 snippet.js:41 pop image : file:/// ... /img/image1.jpg delay : 2000 snippet.js:41 pop image : file:/// ... /img/image2.jpg delay : 2000 snippet.js:41 pop image : file:/// ... /img/image3.jpg delay : 2000 snippet.js:41 pop image : file:/// ... /img/image4.jpg delay : 2000 snippet.js:41 pop image : file:/// ... /img/image5.jpg delay : 2000 snippet.js:41 pop image : file:/// ... /img/image6.jpg delay : 10000 snippet.js:41 show noise snippet.js:38 undefined 

问题是您没有在此行中传递函数。 你实际上称之为this.showImages

 $("#img").fadeIn(0).delay(imageToShow.delay).fadeOut(0, this.showImages(imageArray)); 

您需要传递一个匿名函数,该函数在调用时执行this.showImages

 var self = this; $("#img").fadeIn(0).delay(imageToShow.delay).fadeOut(0, function() { self.showImages(imageArray); }); 

而且我认为你还需要删除$("#img").show();