本文介绍了每次调用迭代循环以达到设置的迭代次数,直到数组结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预加载图像功能,每次调用它时,我想使用它来预加载2张图像,直到所有图像都被预加载.这是我的功能:

I have a preload images function which I would like to use to preload 2 images each time it is called, until all the images are preloaded.This is my function:

function preload() {
  for (i; i < images.length; i++) {
    images[i] = new Image()
    images[i].src = '/imagecache/cover/' + images[i]
  }
}

我不确定如何实现这一点,以便每次调用时都可以更改开始次数和迭代次数(2),直到预加载整个图像数组为止?

I am not sure how to achieve that, to be able to change start and number of iterations (2) each time it is called, until the whole array of images is preloaded?

已更新

这是我的完整剧本:

 $(document).ready(function () {
    var imagesIndex = 0;
    var loadedImages = new Array();
    var nextImage = 0;
    preload();

    function preload() {
        for (i = 0; i < 2; i++) {
            if (nextImage < images.length) {
                var img = new Image();
                img.src = '/imagecache/cover/' + images[nextImage];
                loadedImages[nextImage] = img;
                ++nextImage;
            }
        }
    }

    $('#forward').click(function() {
      imagesIndex++;
      preload();

      if (imagesIndex > (loadedImages.length - 1)) {
          imagesIndex = 0;
      }

      $('#image').attr({"src" : '/imagecache/cover/' + loadedImages[imagesIndex], "alt" : name});
    });

    $('#back').click(function() {
        imagesIndex--;

        if (imagesIndex < 0) {
            imagesIndex = (loadedImages.length - 1);
        }

        $('#image').attr({"src" : '/imagecache/cover/' + loadedImages[imagesIndex], "alt" : name});
    });
});

这里有前进和后退函数,我想在它们上调用preload函数进行2次迭代.

Here I have forward and back functions on which I would like to call preload function to iterate 2 times.

推荐答案

跟踪函数外部数组中的位置.但是首先,您必须解决以下问题:使用Image对象 之前,我会覆盖我假定的图像URL.

Keep track of where you are in the array outside the function. But first, you have to fix the problem that you're overwriting what I assume is the URL of the image with the Image object before you grab that URL.

例如:

var nextImage = 0;
function preload() {
    preload1();
    preload1();
}
function preload1() {
    if (nextImage < images.length) {
        var img = new Image();
        img.src = '/imagecache/cover/' + images[nextImage];
        images[nextImage] = img;
        ++nextImage;
    }
}

当然,您可以使用循环代替preload1.

Of course, you could use a loop instead of preload1.

这篇关于每次调用迭代循环以达到设置的迭代次数,直到数组结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:15