gpt4 book ai didi

javascript - jQuery while 循环不起作用

转载 作者:行者123 更新时间:2023-11-30 06:58:19 26 4
gpt4 key购买 nike

我只是想弄清楚如何循环遍历具有相同类的元素并一次为它们制作动画。我认为这个 while 循环可以工作,但我不明白为什么它不会。

$(document).ready(function() {
var index = 0;
var images = $('.image');

while (index < images.length) {
var image = images[index];
image.animate({
opacity: "1"
}, 1000, function() {
index++;
});
};
});

这是 Fiddle

最佳答案

这是@Evert brilliantly explains in another answer 的简单实现。 .

在这里引用他们的回答

index++ is called in a callback that's executed after the animation. The animation would only start after this script has stopped executing.

Because of this, index++ never gets executed and the loop never ends.

You need to rewrite this as a recursive function. The event handler that now calls index++ actually needs to be responsible for setting up the next animation.

实现可以是这样的

var index = 0;
var images = $('.image');
animate(images);

function animate() {
var image = images.eq(index);
image.animate({
opacity: "1"
}, 1000, function () {
index++;
animate();
});
}

演示 https://jsfiddle.net/dhirajbodicherla/w4cgctyk/2/

关于javascript - jQuery while 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31482201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com