即使在 DOM 加载后也无法设置 null 的 .innerHTML
Cannot set .innerHTML of null even after DOM load
我不断收到错误"无法设置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! 天啊。。。
咳咳,挨了一拳。
相关文章:
- 数组在递归方法中设置为null
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- jQuery Modal Popup-回发后输入类型设置为null
- 无法设置属性'innerHTML'在javascript中为null
- JQuery在设置另一个值之前将附加值设置为null
- 如果为null,则设置javascript变量的值
- 为什么设置 element.className = null 会导致 class=“null”
- 未捕获的类型错误:无法设置属性'onclick'为null.已尝试window.onload
- Highcharts无法设置属性'的值;要点':对象为null或未定义
- 即使在 DOM 加载后也无法设置 null 的 .innerHTML
- 通过JavaScript设置null值
- 未捕获的类型错误:将 innerhtml 设置为数组中的字符串时,无法设置 null 的属性 'innerHTM
- HTML 错误无法设置 null 属性(匿名函数)
- 如果一个组不匹配,如何设置 NULL
- 未捕获的类型错误:无法设置 null.active 的属性“类名”
- 未捕获的类型错误:无法设置null的属性
- 无法设置null错误的innerHTML.尽管存在html ID
- 在javascript中设置null变量值为默认值
- 不能读取property 'removeChild'使用JSP设置null
- JavaScript 错误 msg : 未捕获的类型错误: 无法设置 null 的属性 'onclick'