在javascript中通过数组设置间隔

在javascript中通过数组设置间隔,javascript,Javascript,如何通过数组设置间隔或超时,以每2秒为元素生成效果例如,第一个想法是编程如下: for (photoKey in arrBigPhotoes) { setInterval(function() { // alert(arrBigPhotoes[photoKey]); document.getElementById("big_photo").src='/upload/images/'+arrBigPhotoes[photoKey];

如何通过数组设置间隔或超时,以每2秒为元素生成效果例如,第一个想法是编程如下:

for (photoKey in arrBigPhotoes) {
      setInterval(function() {
        // alert(arrBigPhotoes[photoKey]);

          document.getElementById("big_photo").src='/upload/images/'+arrBigPhotoes[photoKey];

      }, 2000);
}
但它没有正常工作。也许有人能帮我完成这项任务,我会非常高兴的。 我还有一个jQuery——解析可能通过这个库,但没有任何插件。
谢谢。

试试这样的东西-

var photos = ['1.jpg', '2.jpg', '3.jpg'];
var photo_index = 0;

function switchPhoto() {
  photo_index = (photo_index + 1) % photos.length;
  document.getElementById('big_photo').setAttribute('src', '/upload/images/' + photos[photo_index]);
}

setInterval(switchPhoto, 2000);

您可能应该将其放入某种文档就绪事件处理程序中

var photos = ['1.jpg', '2.jpg', '3.jpg'];
var photo_index = 0;

function switchPhoto() {
  photo_index = (photo_index + 1) % photos.length;
  document.getElementById('big_photo').setAttribute('src', '/upload/images/' + photos[photo_index]);
}

setInterval(switchPhoto, 2000);

您可能应该将其放入某种文档就绪事件处理程序中,我建议您预加载要显示的图像。如果用户的连接速度较慢,您的方法将失败

var images = new Array();
var counter = 0;

var image = document.createElement("img");
image.onload = function() {
    counter++;
};
image.src = <url>;
images.push(image);
计数器在那里,以便您可以确定何时正确加载所有图像。假设您有六个图像,然后在插值函数中,如果计数器<6,您将立即返回

您的切换功能可能是这样的

var i = 0;

setInterval(function() {
    if (counter < 6) return;

    i = (i+1) % images.length;
    document.getElementById("big_photo").src = images[i].src;
}, 2000);

我建议您预加载要显示的图像。如果用户的连接速度较慢,您的方法将失败

var images = new Array();
var counter = 0;

var image = document.createElement("img");
image.onload = function() {
    counter++;
};
image.src = <url>;
images.push(image);
计数器在那里,以便您可以确定何时正确加载所有图像。假设您有六个图像,然后在插值函数中,如果计数器<6,您将立即返回

您的切换功能可能是这样的

var i = 0;

setInterval(function() {
    if (counter < 6) return;

    i = (i+1) % images.length;
    document.getElementById("big_photo").src = images[i].src;
}, 2000);

你能澄清一下什么是工作不正常吗?所有的东西都被分配到同一张照片上吗?你能澄清一下什么是工作不正常吗?所有的东西都分配给同一张照片吗?是的,数学机械化的照片索引=照片索引+1%照片长度;非常感谢,我只添加了SetIntervalsSwitchphoto,2000;在document.ready语句中-工作完美。我想知道为什么除了src之外你还使用setAttribute?只是习惯-我不记得为什么我开始使用它,但我相信我遇到了一个直接访问属性不起作用的情况,所以我总是使用setAttribute来保持一致性;非常感谢,我只添加了SetIntervalsSwitchphoto,2000;在document.ready语句中-工作完美。我想知道为什么除了src之外你还使用setAttribute?只是习惯而已-我不记得我为什么开始使用它,但我相信我遇到了一个直接访问属性不起作用的情况,所以我总是使用setAttribute来保持一致性。