求助:Cannot read property 'addEventListener' of null错误排查
解决Uncaught TypeError: Cannot read property 'addEventListener' of null错误及代码优化
错误原因
你的JavaScript脚本放在了<body>标签之前,浏览器解析HTML是从上到下执行的,当脚本运行时,页面里的<input id="clicker">等DOM元素还没被创建出来,所以document.getElementById("clicker")返回null,调用null.addEventListener就会抛出这个错误。
解决方法
有三种常见的修复方式:
方法1:将脚本移到末尾
把<script>标签移到</body>前,确保所有DOM元素加载完成后再执行脚本:
<!DOCTYPE html> <html> <head> <title>The Verification Game</title> <link rel="stylesheet" href="./starting.css"> </head> <body> <div id="underneath"> <h2>Are you a human?</h2> <input type="checkbox" id="realclicker"> </div> <div id="maincheck"> <h2>Are you a robot?</h2> <input type="checkbox" id="clicker"> </div> <div id="incorrect"> <div id="inner"> <h1 class="fancytext">So you are a robot? You can't come here.</h1> </div> </div> <!-- 脚本移到此处 --> <script src="https://kit.fontawesome.com/1f2023aaf1.js" crossorigin="anonymous"></script> <script src="verification.js"></script> </body> </html>
方法2:用DOMContentLoaded事件包裹代码
在JS里监听DOMContentLoaded事件,等DOM加载完成后再执行元素获取和事件绑定逻辑:
document.addEventListener('DOMContentLoaded', function() { const flareup = document.getElementById("incorrect") const checker = document.getElementById("clicker") const maincheck = document.getElementById("maincheck") checker.addEventListener("mousedown", function(event){ if(event.button === 0){ // 左键点击 console.log("Ok") if(checker.checked){ // 直接判断复选框状态 console.log("I am here") flareup.style.display = "block" } } else if(event.button === 2){ // 右键点击(注意是2,1是中键) maincheck.classList.add("animationclass") // 用classList.add避免覆盖原有类 } }) // 阻止右键默认菜单,避免干扰交互 checker.addEventListener('contextmenu', function(e) { e.preventDefault(); }); })
方法3:给script标签加defer属性
在脚本标签上添加defer,让浏览器在DOM解析完成后再执行脚本,同时不阻塞HTML解析:
<script src="verification.js" defer></script>
其他代码优化点
- 事件函数必须传入
event参数,否则严格模式下会报错; - 右键对应的
event.button值是2,1代表鼠标中键; - 使用
classList.add()代替直接赋值className,防止覆盖元素原有类名; - 判断复选框状态时,直接写
checker.checked即可,无需== true; - 监听
contextmenu并阻止默认行为,避免右键弹出浏览器默认菜单影响交互。
内容的提问来源于stack exchange,提问作者cfrrf
相关产品推荐
相关产品推荐

