js事件处理程序 Uncaught TypeError: Cannot read property 'addEventListener' of null
来源:互联网 发布:学校三级公共卫生网络 编辑:程序博客网 时间:2024/06/06 03:32
在写跨浏览器的事件处理程序时,遇到这个bug:
Uncaught TypeError: Cannot read property 'addEventListener' of null
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><button class="btn">跨浏览器的事件处理程序</button><script> var btn = document.getElementById('btn'); var handler = function () { alert('clicked'); }; var EventUtil = { addHandler : function (element, type, handler) { if (element.addEventListener) { // DOM2级 事件处理程序 element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent('on' + type, handler); // IE 事件处理程序 } else { element['on' + type] = handler; // DOM0级 事件处理程序 } }, removeHandler : function (element, type, handler) { if (element.addEventListener) { // DOM2级 事件处理程序 element.removeEventListener(type, handler, false); } else if (element.attachEvent) { element.detachEvent('on' + type, handler); // IE 事件处理程序 } else { element['on' + type] = null; // DOM0级 事件处理程序 } } }; EventUtil.addHandler(btn, 'click', handler);</script></body></html>
意思是,不能读取 null 中的 addEventListener 属性。
由上面的代码可以看到,获取 button 元素时,使用的是 getElementByIDd, 而HTML中buttont 添加的是的是 class 属性,所以脚本中的 btn 变量是 null;
阅读全文
0 0
- js事件处理程序 Uncaught TypeError: Cannot read property 'addEventListener' of null
- cocos2d-js-----Uncaught TypeError: Cannot read property 'style' of null
- js提示Uncaught TypeError: Cannot read property 'options' of null
- 网页html错误:Uncaught TypeError: Cannot read property 'addEventListener' of null
- Uncaught TypeError: Cannot read property 'addEventListener'
- Uncaught TypeError: Cannot read property of 'name' null
- Uncaught TypeError: Cannot read property 'length' of null
- Uncaught TypeError: Cannot read property 'length' of null
- Uncaught TypeError: Cannot read property 'value' of null
- 【ExtJS】Uncaught TypeError: Cannot read property 'length' of null
- openlayers Uncaught TypeError: Cannot read property 'wrapDateLine' of null
- Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
- Uncaught TypeError: Cannot read property 'value' of null
- Uncaught TypeError: Cannot read property 'width' of null
- JavaScript:Uncaught TypeError Cannot read property 'id' of null。
- Uncaught TypeError: Cannot read property 'childNodes' of null
- Uncaught TypeError: Cannot read property 'offsetTop' of null
- Uncaught TypeError: Cannot read property 'value' of null
- Pow(x, n)---lintcode
- 查看javaScrip代码定义
- VC++6.0总报错的问题 : Error spawning cl.exe
- Python读取文本绘制动态速度曲线(多图同步显示)
- [题解] P2015 二叉苹果树(树形DP)
- js事件处理程序 Uncaught TypeError: Cannot read property 'addEventListener' of null
- 汇哲科技-8月23日国盟CISA每日一题
- 结构体、共用体与枚举
- 餐饮行业的运营
- tf.get_collection获取训练变量等效用法
- 指针为空的崩溃
- 最长公共子串
- 成为JavaGC专家(3)—如何优化Java垃圾回收机制
- IntelliJ删除行快捷键