zoukankan      html  css  js  c++  java
  • Cannot set property 'onclick' of null的问题

    转载自: https://my.oschina.net/ximidao/blog/351017

    摘要: 测试点击事件的时候浏览器报错,提示Uncaught TypeError: Cannot set property 'onclick' of null

    今天看了一个W3School JS点击事件的测试案例,详情页:http://www.w3school.com.cn/tiy/t.asp?f=js_dom_event_onclick4,其代码为:

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>

    <p>点击按钮就可以执行 <em>displayDate()</em> 函数。</p>

    <button id="myBtn">点击这里</button>

    <script>
    document.getElementById("myBtn").onclick=function(){displayDate()};
    function displayDate()
    {
    document.getElementById("demo").innerHTML=Date();
    }
    </script>

    <p id="demo"></p>

    </body>
    </html>

    点击效果正常,而我平时测试代码的时候一般习惯把JS代码写在head标签里面,上述的代码如果将JS代码移到head标签,浏览器就会报错,提示:Uncaught TypeError: Cannot set property 'onclick' of null。

    分析了一下代码,W3School的写法是浏览器先加载完按钮节点才执行的JS,因此我将代码改为:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script>
    window.onload=function(){
    document.getElementById("myBtn").onclick=function(){displayDate()};
    function displayDate(){
    document.getElementById("demo").innerHTML=Date();
    }
    }

    </script>
    </head>
    <body>

    <p>点击按钮就可以执行 <em>displayDate()</em> 函数。</p> <button id="myBtn">点击这里</button>

    <p id="demo"></p>


    </body>
    </html>

    测试通过,说明节点需要先加载完才能执行onclick事件。

  • 相关阅读:
    oracle 11g 执行先决条件检查失败的解决方法
    Oracle 11g 详细安装步骤
    Github的使用
    Git的配置与基本操作
    Git安装教程(windows)
    robot framework 自动化框架环境搭建
    Windows下jenkins环境搭建
    Windows 下搭建 SVN服务器
    fiddler配置及使用教程
    逆序链表
  • 原文地址:https://www.cnblogs.com/jeacy/p/6501819.html
Copyright © 2011-2022 走看看