gpt4 book ai didi

Javascript innerHTML 将变量显示为 0

转载 作者:行者123 更新时间:2023-11-28 07:13:12 25 4
gpt4 key购买 nike

我试图使用innerHTML来显示一个变量,该变量通过json文件中的循环运行并添加到自身上,但是当使用innerHTML添加它时,它显示为0。我使用console.log来确保它正在按应有的方式添加数字,而且确实如此,所以我不太确定问题是什么(对我放轻松,我今天确实开始使用 Javascript)。
控制台日志:/image/0eSKH.png
它在网页中的样子:/image/fGMK5.png
我的 JavaScript:

window.onload = function() {
//Creates variable count
var count = 0;
//Runs through json file in a loop so the count can find the object amount
$.getJSON("/quake/quake.txt", function(json1) {
$.each(json1, function(key, data) {
count = count + 1;
count = count - (Number(data.mag) < 3.1);
console.log(count);
});
});
//Displays count in element with ID quakecount
document.getElementById("quakecount").innerHTML += "Magnitude 3.1+ Earthquakes Displayed: " + count;

}

最佳答案

$.getJSON异步,它不会等待文件加载,它会移动到下一行,因此每次你得到 0,将您的 innerHTML 移至此函数中,它将正常工作。:

window.onload = function() {
//Creates variable count
var count = 0;
//Runs through json file in a loop so the count can find the object amount
$.getJSON("/quake/quake.txt", function(json1) {
$.each(json1, function(key, data) {
count = count + 1;
count = count - (Number(data.mag) < 3.1);
console.log(count);
});
//Displays count in element with ID quakecount
document.getElementById("quakecount").innerHTML += "Magnitude 3.1+ Earthquakes Displayed: " + count;

});
}

关于Javascript innerHTML 将变量显示为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31096559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com