无法读取null的属性* 0 * [英] Cannot read property *0* of null
问题描述
我收到此错误无法读取null的属性'0'."
I get this error "Cannot read property '0' of null."
我有一张桌子
somename.html
somename.html
<table>
<tr>
<td id="td1">text</td>
</tr>
</table>
somename.js
somename.js
function test(){
var date=new Date();
if(date.getDay()==1 && date.getHours() >=13 && date.getMinutes() >=3 ){ //8-9AM
document.getElementById('td1')[0].style.color = 'blue';
}else if(date.getDay()==1 && date.getHours() == 14 && date.getMinutes() <= 20){
document.getElementById('td1')[0].style.color = 'blue';
}else{
//nothing
}
}
setInterval(test(),1000);
如果我删除[0]无法读取null的属性'样式',则为新错误"
new error if i remove [0] "Cannot read property 'style' of null"
推荐答案
getElementById
返回 null
.(这将导致您准确地收到错误消息).
getElementById
returns null
if there is no match in the document. (Which then leads to exactly your error message).
这意味着您在选择器中输入了错字,或者在将元素包含到dom中之前执行了html或js.
This means that either you have a typo in your selector or the html or the js gets executed before your element is included into the dom.
此外, getElementById
返回单个元素而不是数组(准确地说是 Node List
),因此正确的调用将是:
Also, getElementById
returns a single element and not an array (Node List
to be precise), so the correct call would be:
document.getElementById('td1').style.color = 'blue';
第三个问题:
setInterval(test(),1000);
// /\
// this will immeditately execute the function and
// hands over the *return value* to setInterval
将无法正常工作,它必须是
will not work as intended, it needs to be
setInterval(test,1000);
// /\
// hand over the *function reference* to be executed after 1 second
这篇关于无法读取null的属性* 0 *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!