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

时间:2013-11-25 16:03:02

标签: javascript jquery callback delay

重写的代码应显示任意数量的图片,旧代码是静态的。 但新代码的作用是立即显示阵列的最后一个图像,并将所有图像完全延迟显示在一起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文件

<!DOCTYPE html>

<html>
 <script src="jquery.js"></script>
<body>

<div id="flick">

    <img id="noise" src="noise2d.png" style="display: ; height: 400px; width: 400px;" class="flickImg">

    <img id="img" src="" style="display: none ; height: 400px; width: 400px;"     class="flickImg">


</div>

</body>
<script src="snippet.js"></script>
</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

1 个答案:

答案 0 :(得分:2)

问题是你没有在这一行传递函数。你实际上打电话给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();