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

Cannot set .innerHTML of null even after DOM load

我一直收到错误 "Cannot set .innerHTML of null"。我也试过在最后一个 body 标签之前链接脚本。我一直使用双引号,所有内容都拼写正确,并且脚本运行。我注意到 weatherBox div 中的两个 div 仍然没有加载。它们不会出现在开发工具中。

我可以将温度值注入 weatherBox 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 的innerHTML 删除了#current!天哪...

Ack,当机立断。