即使在 DOM 加载后也无法设置 null 的 .innerHTML

Cannot set .innerHTML of null even after DOM load

本文关键字:设置 null innerHTML DOM 加载      更新时间:2023-09-26

我不断收到错误"无法设置null的.innerHTML"。我也尝试在最后一个正文标签之前链接脚本。我始终使用双引号,所有内容拼写正确,脚本运行。我注意到 weatherBoxdiv 中的两个div 仍然没有加载。它们不会显示在开发工具中。

我可以将温度值注入天气盒div,它就会出现。但这不是我想要的地方。

该 HTML:

<p>Stuff should load here:</p>
<div id="weatherBox">
    <div id="current"></div>
    <div id="forecast"></div>
</div>

JS:

window.onload = function() {
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function(){
    if(myRequest.readyState === 4){
        if(myRequest.status ===200){
        document.getElementById("weatherBox").innerHTML = "load success. see console.";
        var weather = JSON.parse(myRequest.responseText);
        console.log(weather);
        document.getElementById("current").innerHTML = weather.current_observation.feelslike_f;
        } 
    }
};
myRequest.open("GET", "http://api.wunderground.com/api/ceb5d155ada684a6/forecast/geolookup/conditions/q/WI/Oshkosh.json");
myRequest.send();
};

问题是,当您在 <div id="weatherBox"> 上设置innerHTML时,您将完全替换内容。

document.getElementById("weatherBox").innerHTML = "load success. see console.";

<div id="current"></div>元素从<div id="weatherBox">中删除。

<div id="weatherBox">
    <div id="current"></div>
    <div id="forecast"></div>
</div>

然后,当您在擦除此元素后尝试访问此元素时,它会失败。

document.getElementById("current").innerHTML = weather.current_observation.feelslike_f;

您通过设置 #weatherBox 的内部 HTML 删除了 #current! 天啊。。。

咳,挨了一拳。