我正在尝试从嵌套匿名函数中破坏一个for循环(标记为),如下所示:

function ajax(iteration, callback) {
    var rtrn, xh;
    if (window.XMLHttpRequest) {
        xh = new XMLHttpRequest();
    } else {
        xh = new ActiveXObject("Microsoft.XMLHTTP");
    };
    xh.onreadystatechange = function() {
        if (xh.readyState == 4 && xh.status == 200) {
            callback(xh.responseText);
        };
    };
    xh.open("GET", "file.php?i=" + iteration, true);
    xh.send();
};

var atk_delay = 100;
loop:
for(i = 1; i <= 40; i++) {
    var to = atk_delay * i;
    setTimeout(
        function() {
            ajax(i, function(responseText) {
                var div = document.getElementById("combat");
                div.innerHTML += responseText;
                var arrRt = responseText.split("::");
                if(arrRt[0] == "stop") {
                    break loop;
                };
            });
        },
    to);
};


我真的不知道该如何解决。显然,问题在于它找不到标签。我该如何解决?

最佳答案

所以我解决了!感谢您的帮助!您让我意识到我需要一种完全不同的方法!

function ajax(callback) {
    var rtrn, xh;
    if (window.XMLHttpRequest) {
        xh = new XMLHttpRequest();
    } else {
        xh = new ActiveXObject("Microsoft.XMLHTTP");
    };
    xh.onreadystatechange = function() {
        if (xh.readyState == 4 && xh.status == 200) {
            callback(xh.responseText);
        };
    };
    xh.open("GET", "file.php", true);
    xh.send();
};

var atk_delay = 100;

function roll() {
    ajax(function(responseText) {
        var div = document.getElementById("combat");
        div.innerHTML += responseText;
        var arrRt = responseText.split("::");
        if(arrRt[0] == "cont") {
            setTimeout(roll, atk_delay);
        };
    });
};

setTimeout(roll, atk_delay);

关于javascript - 从匿名函数中中断for循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20134671/

10-09 21:31