【问题标题】:Cannot read property *0* of null无法读取属性 *0* of null
【发布时间】:2018-03-23 22:12:51
【问题描述】:

我收到此错误“无法读取 null 的属性 '0'。”

我有一张桌子

somename.html

<table>  
    <tr>  
    <td id="td1">text</td>  
    </tr>  
    </table>

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 的属性‘样式’”

【问题讨论】:

  • java.js 让我像php.py 一样畏缩 :)
  • 问题是document.getElementById('td1')[0] 我猜
  • 使用setInterval(test,1000);
  • @Satpal 将其作为答案发布,但也包括其他所有人对数组索引的修复。
  • 您是否有可能在&lt;head&gt; 部分而不是&lt;body&gt; 部分中拥有此JS 代码?

标签: javascript


【解决方案1】:

getElementById 如果文档中没有匹配项,则返回 null。 (这会导致您的错误消息)。

这意味着要么你的选择器有错别字,要么 html 或 js 在你的元素被包含到 dom 之前被执行。

另外,getElementById 返回单个元素而不是数组(准确地说是Node List),所以正确的调用应该是:

document.getElementById('td1').style.color = 'blue';

第三题:

setInterval(test(),1000);
//              /\
// this will immeditately execute the function and
// hands over the *return value* to setInterval

不会按预期工作,它需要是

setInterval(test,1000);
//            /\
// hand over the *function reference* to be executed after 1 second

【讨论】:

  • 所以如果我在 中链接我的脚本,它不会执行在 中发布的内容?
  • 已修复,我将在 5 分钟内添加为答案,谢谢:D 不知道我必须在 底部发布指向脚本的链接
  • @KevinHaugen - 正确。即使页面尚未完成加载,浏览器实际上也可以运行 JavaScript。我建议您阅读有关事件处理程序的内容,以了解如何让您的代码等待。
  • 是的,我还在努力学习 php、java 和 css,除了 w3school 以外的任何网站都可以帮助我学习吗?
  • @Kevin 为了您自己的利益,您应该避免使用 w3schools,阅读 here why - 还列出了一些非常好的替代资源。
【解决方案2】:

如果您的id 是唯一的,那么这将起作用

document.getElementById('td1').style.color = 'blue';

【讨论】:

  • 这可能只是将错误更改为Cannot read property 'style' of null
【解决方案3】:

当您调用setInterval 时,您必须提供一个函数。您立即调用该函数,而不是将该函数传递给setInterval。应该是:

setInterval(test, 1000);

由于您是立即调用它,它在 DOM 完全加载之前运行,并且找不到 td1 元素。所以getElementById 返回null 而不是元素。

此外,正如其他答案所指出的,您不应使用[0] 访问getElementById 返回的元素。它返回单个元素,而不是 NodeList

【讨论】:

    【解决方案4】:

    document.getElementById('td1') 返回元素,而不是数组。删除[0]

    您还可以在尝试使用之前检查元素是否存在:

    function test() {  
        var elem = document.getElementById('td1');
        if(typeof elem == 'undefined') return;
    
        var date = new Date();
        if(date.getDay()==1 && date.getHours() >=13  && date.getMinutes() >=3 ) { //8-9AM  
            elem.style.color = 'blue';  
        } else if(date.getDay()==1 && date.getHours() == 14  && date.getMinutes() <= 20) {  
            elem.style.color = 'blue';  
        } else {  
          //nothing  
        }  
    }  
    setInterval(test, 1000);
    

    【讨论】:

    • 但是错误信息说它是空的,不是元素。
    • @KevinHaugen 查看 Satpal 的评论。
    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 2018-05-31
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多