我遇到此错误:Uncaught TypeError: Cannot set property 'innerHTML' of null
发出此错误的代码是:
$(document).ready(function() { load(); loadMoney(); for (var i = 0; i < localStorage.length; i++){ var rawItem = localStorage.getItem(localStorage.key(i)); var item = JSON.parse(rawItem); if(item instanceof Array){ var countdownId = setInterval(function(){ var diff = Math.floor((+new Date() - item[0])/1000) if(item[1] < diff){ document.getElementById(item[2]).innerHTML = item[3]; localStorage.removeItem(localStorage.key(i)); clearInterval(countdownId); }else{ document.getElementById(item[2]).innerHTML = item[3] + " Time left: " + calculateTime(item[1]-diff); } },1000); } }
这是对localStorage中的数组的反应,我已经进行了字符串化,这就是:
[1414879430956,2000,&#34; 0id&#34;&#34;倒计时&#34;]
id来自这里,这可能是它给我错误的原因:
function createBus(bus){
var element = document.body.appendChild(document.createElement("div"));
element.className = "bus";
element.style.left = bus.x+"px";
element.style.top = bus.y+"px";
var title = element.appendChild(document.createElement("div"));
title.innerHTML = bus.name;
var button = element.appendChild(document.createElement("button"));
button.id = bus.id*2 + "id";
button.innerHTML = "Ok, send off ";
button.onclick = function(){
startCountDown(bus.time, button.id, bus.name);
}
button.className = "pure-button";
var icon = button.appendChild(document.createElement("i"));
icon.className = "fa fa-bus"
return element;
}
我怀疑这是在函数运行之前没有创建的div中的错误,因为如果我运行
document.getElementById("0id").innerHTML = ...
然后它有效。
提前致谢:)
答案 0 :(得分:0)
这是一个评论,但我想要一些格式化空间。当你做以下事情时:
document.getElementById(item[2]).innerHTML = item[3];
您希望 getElementById 返回一个节点,因为如果没有,则结果是某个错误。一个更强大的模式是:
var node = document.getElementById(item[2]);
if (node) {
node.innerHTML = item[3];
} else {
// deal with node not being present
}
或类似。