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

如何修复Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

解决计算器按钮点击事件绑定的TypeError问题

错误原因

控制台抛出的Uncaught TypeError: Cannot read properties of null (reading 'addEventListener'),本质是document.querySelector('calc-buttons')未找到目标元素,返回了null。核心问题是类选择器语法错误:calc-buttons是元素的class属性值,使用querySelector选择类时必须以.作为前缀,你漏掉了这个关键符号。

修复方案

1. 修正选择器语法

将document.querySelector('calc-buttons')修改为document.querySelector('.calc-buttons'),确保能正确定位到目标section元素。

2. 可选逻辑优化

为了避免点击按钮外的空白区域(比如.calc-buttons容器本身)触发无效逻辑,可以在事件回调中判断点击目标是否为按钮元素:

修正后的完整script.js代码

function init() {
    document.querySelector('.calc-buttons')
        .addEventListener('click', function (event) {
            // 仅当点击的是计算器按钮时执行逻辑
            if (event.target.classList.contains('calc-button')) {
                console.log(event, "event in init");
                buttonClick(event.target.innerText);
            }
        })
}

init();

额外提示

你的HTML中script标签放在body末尾的写法是合理的,这能保证DOM元素全部加载完成后再执行JS代码,避免元素未初始化导致的null问题。如果后续需要将script标签移到head中,记得用DOMContentLoaded事件包裹初始化逻辑:

document.addEventListener('DOMContentLoaded', init);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:44:55