簡體   English   中英

JavaScript / jQuery:在上一次迭代時重新啟動循環

[英]JavaScript / jQuery : restart for loop on last iteration

我試圖做一個for循環,當它到達最后一次迭代時重新開始。

這是我到目前為止的內容:

    for (var i = 0; i < x + 3; i++) {
    (function(i){
        setTimeout(function(){
            $('#e'+i).animate({'color': '#B2E4FF'}, 500);
            var j = i - 3;
            $('#e'+j).animate({'color': '#A6A5A6'}, 500);
        }, 100 * i);

    }(i));
    if(i == x + 2) {
        i = -1;
        continue;
    }
}

當我添加時continue; 腳本,它將完全停止工作。

我要實現的是動畫滑動漸變文本。 演示1循環: http//puu.sh/aCzrv/98d0368e6b.mp4

完整代碼: http//jsfiddle.net/D6xCe/

問候,

亞歷克斯

不要濫用for循環。
為此使用while循環。

var isCompleted = false;

while(!isCompleted){
// do logic and when completed assign isCompleted = true;

}

編輯
根據您的要求,它應該看起來像這樣:

var isCompleted = false;
var i = 0;
while (!isCompleted) {
    (function (i) {
        setTimeout(function () {
            $('#e' + i).animate({
                'color': '#B2E4FF'
            }, 500);
            var j = i - 3;
            $('#e' + j).animate({
                'color': '#A6A5A6'
            }, 500);
        }, 100 * i);
    }(i));
    if (i == x + 2) {
        i = 0;
    } else if (i == x + 3) {
        isCompleted = true;
    }
    i++;
}

您的代碼有問題
您說如果i < x+3 -> break the loop並且如果i == x+2 -> reset the index and start again.

由於在每次迭代中i都會增加1,因此您嘗試執行“無限循環”。 為此使用while(true)

您將永遠不會達到i == x+3條件,因此您可以將其從我添加的代碼中刪除,並獲得一個無限循環,該循環會根據x + 2迭代后的重置進行邏輯運算。

var i = 0;
while (true) {
    (function (i) {
        setTimeout(function () {
            $('#e' + i).animate({
                'color': '#B2E4FF'
            }, 500);
            var j = i - 3;
            $('#e' + j).animate({
                'color': '#A6A5A6'
            }, 500);
        }, 100 * i);
    }(i));

    i = i == x+2 ? 0 : i+1;
}

您可以將動畫代碼包裝在函數中,並在循環結束后再次重復此函數:

function animate() {
    for (var i = 0; i < x + 3; i++) {
        (function (i) {
            setTimeout(function () {
                var j = i - 3;
                $('#e' + i).animate({color: '#B2E4FF'}, 500);
                $('#e' + j).animate({color: '#A6A5A6'}, 500, function() {
                    if (i == x + 2) {
                        animate();
                    }
                });
            }, 100 * i);
        }(i));
    }
}
animate();

演示: http//jsfiddle.net/D6xCe/2/

如果要執行某個語句的繼續執行,只需要進行不定式循環。形成不定式循環的方法有很多,最簡單的方法是使用while循環。 例如:

while(true)
{
//your statements
}

謝謝

暫無
暫無

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

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