J-query循环问题

J-query loop issues

本文关键字:问题 循环 J-query      更新时间:2023-09-26

我有什么应该是一个简单的jquery延迟图像循环

小提琴在这里

我已经检查了我的语法,我不知道为什么它拒绝工作。

所有的css和代码似乎都是正确的。

函数

$(document).ready(function () {
$.doTimeout('loop', 500, function () {
    //changes the background of img2 to 'i' in 'sequence'
    $(".img2").css('background', 'url(' + sequence[i] + ')');
    //increments 'i' for the next image
    i++;
    //toggles the class 
    $("img1").toggleClass("img2");
    //changes the the background of img1 to 'i' in 'sequence' ready for when class is toggled again
    $(".img1").css('background', 'url(' + sequence[i] + ')');
    //toggles the class
    $("img2").toggleClass("img1");
    //increments 'i; for the next change
    i++;
    //restarts the loop if i is equal to the sequence length
    if (i === sequence.length) {
        i = 0;
    }
});

toggleclass必须在那里,因为我打算稍后添加css3过渡,这将使每个图像在

中褪色

有人能帮帮我吗?

在您的回调中返回True以再次发生循环,它在文档中提到。

$(document).ready(function(){
  // Start a polling loop with an id of 'loop' and a counter.
  $.doTimeout('loop', 500, function(){
     
      $('.img1').css('background', 'url(' + sequence[i] + ')');
      i++;
      return true;
  });
});

另一个问题是,你的循环将打破,因为你的数组将出界,因为你不断增加,而不是使用Array.shift来获得数组的第一个元素和push它回到数组的末尾。有了这个,数组中的元素将在一个循环中运行,你不必维护计数器并重置它等等。

正确的做法是:-

演示
var sequence = ["http://goo.gl/u4QHd",
    "http://goo.gl/s5tmq",
    "http://goo.gl/MMsQ6",
    "http://goo.gl/dtEYw"];
$(document).ready(function(){
  // Start a polling loop with an id of 'loop' and a counter.
  $.doTimeout('loop', 500, function(){
     var url = sequence.shift(); //Remove the first element out of the array
      sequence.push(url); //push it to the end of the array. probably you can put it after the next statement.
      $('#img1').css('background', 'url(' + sequence[0] + ')');//get the first item from the array. this will always be the next one to previous cycle.
      return true;
  });
});