未捕获的类型错误:无法读取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>
答
纠正错字在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>
答
如果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()
你需要在括号中的'if' –
错字@'toLocaleTimeString' ...缺少'e' – Rayon
包围曝光有问题吗?你似乎在'$'(function' –