Cannot set property 'onclick' of null的问题
2014-12-01 00:00
666 查看
摘要: 测试点击事件的时候浏览器报错,提示Uncaught TypeError: Cannot set property 'onclick' of null
今天看了一个W3School JS点击事件的测试案例,详情页:http://www.w3school.com.cn/tiy/t.asp?f=js_dom_event_onclick4,其代码为:
点击效果正常,而我平时测试代码的时候一般习惯把JS代码写在head标签里面,上述的代码如果将JS代码移到head标签,浏览器就会报错,提示:Uncaught TypeError: Cannot set property 'onclick' of null。
分析了一下代码,W3School的写法是浏览器先加载完按钮节点才执行的JS,因此我将代码改为:
测试通过,说明节点需要先加载完才能执行onclick事件。
今天看了一个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事件。
相关文章推荐
- 关于Uncaught TypeError: Cannot set property 'onClick' of null。的问题
- 浏览器出现Cannot set property 'onclick' of null的问题
- 学习笔记3--Cannot set property 'onclick' of null的问题
- JS点击事件——Uncaught TypeError: Cannot set property 'onclick' of null
- Cannot set property 'innerHTML' of null"
- ASP.NET MVC运行出现Uncaught TypeError: Cannot set property __MVC_FormValidation of null的解决方法
- 关于JS出现的Cannot read property 'XXX' of null错误
- Echarts Cannot read property 'modLayer' of null
- Uncaught TypeError: Cannot set property ' ' of null 错误解决
- 关于React “Cannot read property 'setState' of null” 的错误
- Cannot set property ‘innerHTML’ of null 错误原因
- Uncaught TypeError: Cannot set property 'innerHTML' of null
- Error:Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated{apk
- Uncaught TypeError: Cannot set property 'innerHTML' of null
- 关于js Uncaught TypeError: Cannot read property 'style' of null 问题
- Cannot set property ‘innerHTML’ of null 错误原因
- 把script放在head里出现Uncaught TypeError: Cannot set property 'scrollTop' of null(…)
- Cannot set property 'value' of null
- 关于React “Cannot read property 'setState' of null” 的错误
- (JS问题)VM1519:1 Uncaught TypeError: Cannot set property 'planId' of undefined