[英]jQuery while loop not working
我只是想弄清楚如何遍歷具有相同類的元素並一次為其設置動畫。 我認為這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++;
});
};
});
赫雷斯小提琴
在動畫之后執行的回調中調用index++
。 僅在該腳本停止執行后才開始動畫。
因此, index++
永遠不會執行,循環永遠不會結束。
您需要將其重寫為遞歸函數。 現在調用index++
的事件處理程序實際上需要負責設置下一個動畫。
這是@Evert 在另一個答案中精彩解釋的簡單實現。
在這里引用他們的答案
在動畫之后執行的回調中調用index ++。 僅在該腳本停止執行后才開始動畫。
因此,index ++永遠不會執行,循環永遠不會結束。
您需要將其重寫為遞歸函數。 現在調用index ++的事件處理程序實際上需要負責設置下一個動畫。
實現可以是這樣的
var index = 0;
var images = $('.image');
animate(images);
function animate() {
var image = images.eq(index);
image.animate({
opacity: "1"
}, 1000, function () {
index++;
animate();
});
}
還有一個jQuery .each函數,用法如下:
$('.class').each(function() {
$(this).animate();
});
這是該課程的下一個項目
您的邏輯在index++;
出錯了index++;
您應該具有遞歸功能。 您需要在遞歸函數中增加index
的值。
function YourRecusiveFunction() {
var image = images.eq(index);
image.animate({
opacity: '1'
}, 1000, function () {
index++;
YourRecusiveFunction();
});
}
文檔准備好后,調用YourRecusiveFunction()
。
為什么不只使用jQuery each
函數呢?
var images = $('.image');
$.each(images,function(){
$(this).animate({
opacity:"1"
}, 1000, function(){
index++;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.