使用DOMContentLoaded时按钮点击变色失效问题求助
问题修复与解释
你的代码存在几处语法和逻辑错误,导致按钮点击后背景色无变化,逐一说明:
- 拼写错误:
document.addEventListner应为document.addEventListener(单词Listener里的字母e被遗漏),这个错误会直接导致DOMContentLoaded事件监听无法注册,后续代码根本不会执行。 - 回调函数语法错误:你同时混用了普通函数声明
function(event)和箭头函数=>,属于无效语法。正确写法二选一即可,比如function(event) { ... }或者(event) => { ... }。 - 事件对象误用:点击事件回调里的
event.preventDefault()引用的是DOMContentLoaded事件的event对象,而按钮点击本身没有需要阻止的默认行为,这行代码完全多余且逻辑错误。若要在点击事件中使用event,需给点击回调单独传入参数。 - 冗余元素获取:点击事件里通过
document.querySelector('button')获取按钮,其实可以直接用点击事件的目标元素(event.target)或者this,更高效简洁。
修复后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <title>hello</title> <script> // 修正拼写错误,使用正确的回调写法 document.addEventListener('DOMContentLoaded', function() { document.querySelector('#red').addEventListener('click', function() { // 直接使用当前点击的元素 this.style.backgroundColor = 'red'; }); }); </script> </head> <body> <button id='red'> Red </button> </body> </html>
你也可以简化代码:把<script>标签放在</body>之前,此时页面元素已加载完成,无需监听DOMContentLoaded事件,代码更简洁:
<!DOCTYPE html> <html lang="en"> <head> <title>hello</title> </head> <body> <button id='red'> Red </button> <script> document.querySelector('#red').addEventListener('click', function() { this.style.backgroundColor = 'red'; }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者David58
相关产品推荐
相关产品推荐

