如何使jQuery每个循环重复无限次

How to make jQuery each loop repeat infinite number of times

本文关键字:无限 循环 何使 jQuery      更新时间:2023-09-26

我正在尝试创建一个幻灯片,并在每个图像循环后重复each循环。我已经尝试了所有的方法,但在循环通过每个图像后无法继续循环。请查看我的代码并在下面尝试。

有人有什么想法吗?什么都试过了。

html

<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-3.jpg" />

js

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    });
   if(index === 3){
      index = 0;
   }
}
test();

您应该在间隔后再次启动循环,而无需重置索引(这也完全不起作用)。

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    });
    setTimeout(test,9400)
}
test();

由于有三个img,每个img显示的延迟为3000,而fadeOut默认情况下需要400毫秒,因此延迟应为:

3*3000+400=9400

请注意,每个下一个fadeIn都不等待上一个fade Out的完成,因此窃取了fade Out前两个400ms的延迟。

您最好的选择是使用promise:

function test() {
    $("img").hide().each(function(index) {
        $(this).delay(3000 * index).fadeIn(3000).fadeOut();
    }).promise().done(test);
}
test();

-jsFiddle-