未捕获的类型错误:无法读取null错误的属性'innerHTML'

问题描述:

我正在刷新每1秒后显示的时间。我尝试用元素divMessage中的文字作为该显示的前缀。但是,我不断收到错误“Uncaught TypeError:无法读取属性'innerHTML'null”错误。但是,文档准备功能($function())divMessage的文本没有任何问题。那么,这里发生了什么?未捕获的类型错误:无法读取null错误的属性'innerHTML'

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script type="text/javascript"> 
    var myVar = setInterval(myTimer, 1000); 
    var loaded = false 

    $(function(){ 
     .... 
    $.post(window.location, { 
     .... 
    }).success(function(data){ 
     // I assign divMessage text here without any problems! 
     loaded = true 
    }); 

    function myTimer() 
    { 
     var d = new Date() 
     var dateTime = d.toLocaleTimeString() 
     var divMessage = '' 
     if (loaded) { 
      // Uncaught TypeError: Cannot read property 'innerHTML' of null" error here! 
      divMessage = document.getElementById("divMessage").innerHTML 
      document.getElementById("div2").innerHTML = "<span style=\"color:green\">" + 
       divMessage + ", " + dateTime + "</span>"; 
     } 
    } 
</script> 
</head> 

这些元素是这样定义的。

<div id="divMessage"><span style="color:yellow">some text</span></div> 
<div id="div2"><span style="color:yellow">some text</span></div> 
+0

你需要在括号中的'if' –

+0

错字@'toLocaleTimeString' ...缺少'e' – Rayon

+2

包围曝光有问题吗?你似乎在'$'(function' –

纠正错字在toLocaleTimeString和删除多余的})括号

var myVar = setInterval(myTimer, 1000); 
 
var loaded = false; 
 

 
$(function() { 
 
    loaded = true 
 
}); 
 

 
function myTimer() { 
 
    var d = new Date() 
 
    var dateTime = d.toLocaleTimeString(); 
 
    var divMessage = '' 
 
    if (loaded) 
 
    divMessage = document.getElementById("divMessage").innerHTML 
 
    document.getElementById("div2").innerHTML = "<span style=\"color:green\">" + 
 
    divMessage + ", " + dateTime + "</span>"; 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
<div id="divMessage"><span style="color:yellow">some text</span> 
 
</div> 
 
<div id="div2"><span style="color:yellow">some text</span> 
 
</div>

+0

实际上,额外的括号是因为我有一些代码,当我试图以简化的方式显示我的代码时,我忘记删除它。问题仍然存在! – pythonic

+0

@Downvoter,可能是我错了...但突出显示错误,以便我可以更正它... – Rayon

+0

@pythonic - 您是否运行了代码?那失败了吗? – Rayon

如果divMessage没有在页面加载DOM存在,getElementById将返回null。

Elements not in the document are not searched by getElementById(). When creating an element and assigning it an ID, you have to insert the element into the document tree with Node.insertBefore() or a similar method before you can access it with getElementById()