簡體   English   中英

我如何在for循環后直到for循環完成其交互之前不運行代碼?

[英]How do I get the code after the for-loop to not run until the for-loop has completed its interations?

在for循環完成所有交互之前,如何停止運行警報功能?

 $(document).ready(function() {
    for (i = 1; i <= 8; i++) {
        $('#ponyDiv').animate({left: '200px'}, 2000); 
    }
    alert("here");
});

編輯:在循環中調用animate()時,可以執行以下操作:

$(document).ready(function () {
    var completed = 0;
    for (i = 1; i <= 8; i++) {
        $('#ponyDiv'+i).animate({
            left: '200px'
        }, 200, function () {
            if (completed++ == 7) alert("here");
        });
    }
});

使用JQuery animate() 'complete'回調,動畫完成后立即調用:

  $('#ponyDiv').animate({left: '200px'}, 2000, function() {
    alert('here');
  });

這將在循環完成時發出警報(而不是在最終動畫完成時發出警報)。

$(document).ready(function() {
    for (i = 1; i <= 8; i++) {
        $('#ponyDiv' + i).animate({left: '200px'}, 2000);
        if(i === 8){
            alert("here");
        }
    }    
});

推遲使用:

$.when($('[id^=pony]').animate({left:'200px'},2000))
    .then(function() { alert('done'); });

當然,使用類比以id開頭的屬性更好,但是您可以從中了解要點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM