报错‘button.addEventListener is not a function’及responseToClick显示void的问题求助
问题分析与修复方案
错误原因拆解
button.addEventListener is not a function报错document.querySelectorAll("button")返回的是NodeList类数组集合,不是单个DOM元素,只有单个DOM元素才具备addEventListener方法。你需要遍历这个集合,给每个按钮单独绑定点击事件。h3Tag.textContent("Foo")语法错误textContent是DOM元素的属性,不是方法,不能用函数调用的方式赋值,应该直接通过赋值操作设置内容。关于
responseToClick显示void
这不是错误,你的函数没有写return语句,默认返回undefined,编辑器会标注为void表示无返回值,属于正常现象,不影响功能运行。
修正后的代码
const buttons = document.querySelectorAll("button"); const body = document.querySelector("body"); // 遍历按钮集合,给每个按钮绑定点击事件 buttons.forEach(button => { button.addEventListener('click', responseToClick); }); function responseToClick() { const h3Tag = document.createElement('h3'); h3Tag.textContent = "Foo"; // 修正属性赋值方式 body.appendChild(h3Tag); }
内容的提问来源于stack exchange,提问作者David Boell
相关产品推荐
相关产品推荐

