You need to enable JavaScript to run this app. 调用事件监听器无响应返回null、addEventListener属性读取失败问题
优惠活动
大模型
产品
解决方案
定价
更多

调用事件监听器无响应返回null、addEventListener属性读取失败问题

问题原因与修复方案

1. 核心错误:选择器语法错误

你使用querySelector查找按钮时,没有加对应的选择器前缀:

  • 如果按钮是用class="prev-btn"定义的,需要加.前缀,写成.prev-btn
  • 如果是用id="prev-btn"定义的,需要加#前缀,写成#prev-btn
    你当前直接写querySelector("prev-btn")会匹配标签名为prev-btn的元素,页面中不存在这种自定义标签,所以返回null,调用addEventListener自然就触发了Cannot read property 'addEventListener' of null的报错。

2. 优化项:执行顺序调整

你现在的元素获取、事件绑定代码都是在全局作用域同步执行的,如果你的JS代码放在HTML的<head>标签里,执行时DOM还没渲染完成,就算选择器写对了也可能拿到null。建议把元素获取、事件绑定逻辑都移到DOMContentLoaded的回调函数里,保证DOM加载完成后再执行相关操作。

修复后参考代码

let currentItem = 0;
// 等DOM加载完成后再执行所有DOM操作、事件绑定
window.addEventListener("DOMContentLoaded", function() {
    const img = document.getElementById("person-img");
    const author = document.getElementById("author");
    const job = document.getElementById("job");
    const info = document.getElementById("info");
    // 选择器加对应前缀,此处假设按钮用class定义,所以加.
    const prevBtn = document.querySelector(".prev-btn");
    const nextBtn = document.querySelector(".next-btn");
    const randomBtn = document.querySelector(".random-btn");

    showPerson(currentItem);
    
    function showPerson(person) {
        const item = reviews[person];
        img.src = item.img;
        author.textContent = item.name;
        job.textContent = item.job;
        info.textContent = item.text;
    }

    nextBtn.addEventListener("click", function() {
        currentItem++;
        if (currentItem > reviews.length - 1) {
            currentItem = 0;
        }
        showPerson(currentItem);
    });

    prevBtn.addEventListener("click", function() {
        currentItem--;
        if(currentItem < 0) {
            currentItem = reviews.length - 1;
        }
        showPerson(currentItem);
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 18:15:02