我正在刷新每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>
你需要在括號中的'if' –
錯字@'toLocaleTimeString' ...缺少'e' – Rayon
包圍曝光有問題嗎?你似乎在'$'(function' –