2016-07-27 107 views
-1

我正在刷新每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' –

回答

1

糾正錯字在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

0

如果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()

相關問題