You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错Cannot read properties of null (reading 'addEventListener')求助

解决Cannot read properties of null (reading 'addEventListener')错误

这个错误的核心原因是:你的代码执行时,DOM中还不存在#book-form元素,导致document.querySelector('#book-form')返回null,自然无法调用addEventListener方法。

以下是三种可行的解决办法:

  • 将脚本放在HTML body末尾
    把你的JavaScript代码移到</body>标签之前,这样浏览器会先加载完所有DOM元素,再执行脚本:

    <body>
      <!-- 页面内容,包括#book-form表单 -->
      <form id="book-form">
        <!-- 表单控件 -->
      </form>
    
      <script>
        document.querySelector('#book-form').addEventListener("submit", (e) => {
          e.preventDefault();
          const title = document.querySelector('#title').value;
          const author = document.querySelector('#author').value;
          const pages = document.querySelector('#pages').value;
          const book = new Book(title, author, pages);
          console.log(book)
        });
      </script>
    </body>
    
  • 用DOMContentLoaded事件包裹代码
    监听DOM加载完成事件,确保代码在DOM就绪后执行:

    document.addEventListener('DOMContentLoaded', function() {
      document.querySelector('#book-form').addEventListener("submit", (e) => {
        e.preventDefault();
        const title = document.querySelector('#title').value;
        const author = document.querySelector('#author').value;
        const pages = document.querySelector('#pages').value;
        const book = new Book(title, author, pages);
        console.log(book)
      });
    });
    
  • 给script标签添加defer属性
    如果你的脚本是外部文件,给<script>标签加上defer属性,它会让脚本在DOM解析完成后才执行:

    <script src="你的脚本文件.js" defer></script>
    

另外还要检查两点:

  • 确认HTML中确实存在id="book-form"的表单元素,没有拼写错误
  • 确保Book构造函数已经正确定义,避免后续出现新的错误

内容的提问来源于stack exchange,提问作者struggleRCODE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:03:10