jQuery/JavaScript读取本地文本文件

7
由于某种原因,我卡在了这个“东西”上。
如你所见,我想尝试读取count.txt,这很完美,但由于某种原因,……
alert(code);

即将到来的是在这之后。
alert("The number can't be smaler then 0");

对我来说,这没有意义,因为我会在alert(“The number…”)之前调用alert(count)。有任何想法为什么jQuery函数(alert)会在另一个alert之后被调用?
function leftFunction() {
    jQuery.get('count.txt', function(data) {
        var count = data;
        alert(count);
    });
    scrolling = true;
    if(number == 0) {
        alert("The number can't be smaler then 0");
        return;
    }
    number--;
    document.getElementById("myImage").src = "latest" + number + ".jpg";
}

6
这与同步/异步有关。看看这个链接: https://dev59.com/lV8d5IYBdhLWcg3wRAeE - Red fx
2
jQuery.get() 回调函数是异步的,"如果请求已经完成,则立即触发回调函数。" - guest271314
非常感谢您的帮助 :) - Florian Zaskoku
1个回答

3
正如Red fx在评论中所说,这与JavaScript是异步的有关。尝试使用以下代码代替:
function leftFunction() {
    jQuery.get('count.txt', function(data) {
        var count = data;
        alert(count);
    }).done(function() {
        scrolling = true;
        if (number == 0) {
            alert("The number can't be smaler then 0");
            return;
        }
    });
    number--;
    document.getElementById("myImage").src = "latest" + number + ".jpg";
}

Reference: https://api.jquery.com/jquery.get/


非常感谢您提供的代码片段 :) - Florian Zaskoku

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接