这两个函数都是 $.getJSON()
函数,即使我的第一个函数放在另一个函数之前,它有时也会出现在第二个函数之后。请注意,我提到了“有时”。当我不断刷新页面时,我得到不同的结果,就像是随机选择先调用哪个函数一样。这是代码片段:
timeClusters = [];
$.getJSON('java_output/tasksTab.json', function (data) {
console.log ("first");
// Method stuff here, not important
});
$( document ).ready(function() {
console.log("second");
// Method stuff here, not important
});
现在,当我运行程序并查看控制台时,有时我会得到
first
second
但其他时候我得到
second
first
我必须先获取第一个,然后再获取第二个,因为第二个方法处理第一个方法中生成和更改的数据。
如果您需要更多信息,请告诉我
最佳答案
getJSON
方法是异步的,这意味着一旦启动,它最终将保存一个结果,包装在文档就绪中的函数会在 DOM 准备好后立即触发,而不是执行以下序列您应该将代码从 ready
函数移动到 getJSON
回调:
$(document).ready(function() {
$.getJSON('java_output/tasksTab.json', function (data) {
console.log ("first");
}).done(function() {
console.log( "second" );
})
})
正如 adeneo 指出的那样,您实际上不需要链接 done
方法,您只需在默认回调中添加计算即可:
$(document).ready(function() {
$.getJSON('java_output/tasksTab.json', function (data) {
console.log ("first");
console.log( "second" );
})
})
您可以使用的其他类型的回调有 fail
和 always
。
关于javascript - jQuery 函数未在另一个函数之前执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25171846/