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

无法修改按钮颜色,事件脚本未执行问题排查

代码失效的原因分析

你的代码存在两个关键问题,导致按钮点击后没有交互效果:

  • 节点列表无法直接绑定事件监听:document.querySelectorAll(".incorrect_answer") 返回的是多个元素组成的NodeList(节点列表),这不是单个DOM元素,不能直接调用 addEventListener 方法。必须遍历这个列表里的每个按钮,给每个按钮单独绑定点击事件。
  • CSS属性名拼写错误:正确答案按钮的事件处理代码中,backgoundColor 少写了一个字母 r,正确的属性名应为 backgroundColor,拼写错误会导致样式无法生效。

修正后的代码示例

<!DOCTYPE html>
<html lang="en">
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <link href="styles.css" rel="stylesheet">
        <title>Trivia!</title>
        <script>
            document.addEventListener('DOMContentLoaded', function(){
                // 遍历所有错误答案按钮,逐个绑定点击事件
                let incorrects = document.querySelectorAll(".incorrect_answer");
                incorrects.forEach(button => {
                    button.addEventListener('click', function() {
                        this.style.backgroundColor = 'red';
                    });
                });
                
                let correct = document.querySelector(".correct_answer");
                correct.addEventListener('click', function() {
                    // 修正属性名拼写错误
                    correct.style.backgroundColor = 'green';
                });
            });
        </script>
    </head>
    <body>
        <div class="header">
            <h1>Trivia!</h1>
        </div>

        <div class="container">
            <div class="section">
                <h2>Part 1: Multiple Choice </h2>
                <hr>
                <h3>How many species of Dolphin are there?</h3>
                    <button class="correct_answer">42</button>
                    <button class="incorrect_answer">53</button>
                    <button class="incorrect_answer">24</button>
                    <button class="incorrect_answer">11</button>
            </div>

            <div class="section">
                <h2>Part 2: Free Response</h2>
                <hr>
                <!-- TODO: Add free response question here use input tags -->
            </div>
        </div>
    </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:21:15