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事件。

  • 相关阅读:
    osg模型部分节点旋转
    IFC数据模型构件控制
    自定义基于IFC数据的施工进度数据结构
    QDateTime QString
    Qt获取屏幕分辨率
    Qt自定义类重写 copy
    removeEntry
    initGanttView
    IfcAxis2Placement3D IFC构件的位置和方向
    致我最爱的你
  • 原文地址:https://www.cnblogs.com/jeacy/p/6501819.html
Copyright © 2011-2022 走看看