JavaScript事件添加

使用script脚本为网页中的按钮添加时间,起先代码如下

<body>

  <script>

    document.getElementById("btn").onclick=function(){displayDate()};

    function displayDate(){

    document.getElementById("show").innerHTML = Date();

}

  </script>

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

  <p id="show"></p>

</body>

在火狐的Debug中document.getElementById("btn").onclick=function(){displayDate()};这一句会报is NULL 的错误,所以需要在脚本出现之前定义按钮,但是脚本获取<p>标签并且修改其中的内容似乎没有受到顺序的影响,不知为何?

原文地址:https://www.cnblogs.com/k-q-l/p/3996475.html