一整天都在努力查看代码示例,但无法让它发挥作用。
基本上我想使用四个本地文件中的 HTML 加载一个数组。 然后我将使用该 HTML 用某种动画 slider 动态填充 div。
我的问题是我似乎无法让计时器等待 html 被检索并分配给变量。 GET 工作得很好,但变量似乎没有在 GET 循环之外加载。
我可以看到异步 GET 正确填充了数组,但元素在循环中仍未定义。我认为它们是全局变量,所以不应该是这样。
我是 jQuery 的新手,一直在使用 SO 作为示例,因此欢迎任何建议 - 希望这对于经验丰富的 javascript 编码人员来说只是一个明显的修复。
Here's my code:
window.standings = new Array(4);
window.iURL = 0;
standingsURL = ["MondayNight.html", "TuesdayNight.html", "WednesdayNight.html", "ThursdayNight.html"]
for (window.iURL = 0; window.iURL < window.standings.length; window.iURL ++) {
$.get(standingsURL[window.iURL], function( data ) {
window.standings[window.iURL] = data;
alert (window.standings[window.iURL]);
}, "text");
}
setTimeout(function repeatTimeout() {
if(window.standings[window.standings.length] !== undefined){
for (window.iURL = 0; window.iURL < window.standings.length; window.iURL ++) {
alert (window.standings[window.iURL]);
}
} else {
alert ("Wait again");
setTimeout(repeatTimeout, 2500);
}
}, 1000);
最佳答案
我看到的第一个问题是,在您的 repeatTimeout
函数中,您引用了数组中不存在的项目。
window.stands[window.stands.length]
相当于window.stands[4]
您有一个包含四个项目的数组,并且您在此处引用数组索引 4 - 但数组是零索引的,因此只有索引 0、1、2 和 3 有效。尝试:
window.stands[window.stands.length - 1]
编辑:
声明一个空数组:
window.stands = []
不要使用:window.stands[window.iURL] = data;
,而是执行以下操作:
window.stands.push(数据)
您的 if
函数现在检查长度:
if(window.stands.length === 4)
这是一个相对粗糙的解决方案。查看this SO post有关 when
函数的更多信息。
关于javascript - jQuery - 使用全局数组并等待 $get 加载检索到的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39950962/