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

JavaScript无法修改页面元素:答题验证代码提交后无输出

表单提交无反馈的问题修复

你的代码提交后没有显示结果,核心是存在两处拼写错误,以下是具体修复方案:

1. 按钮类型拼写错误

HTML中按钮的type属性误写为sumbit,正确拼写是submit。错误的类型会导致浏览器无法识别这是表单提交按钮,进而触发不了你绑定的submit事件处理函数。

修复后的按钮代码:

<button id="b" type="submit">Submit</button>

2. 样式属性拼写错误

JavaScript里修改背景色的属性写成了backgrounColor,正确的属性名是backgroundColor(少了字母d)。这个错误会导致输入框颜色无法切换,甚至可能在控制台抛出错误阻断代码执行。

修复后的函数代码:

function wrong2() {
    document.querySelector('#2solution').innerHTML = "Incorrect.";
    document.querySelector('#input').style.backgroundColor = 'red';
}
function right2() {
    document.querySelector('#2solution').innerHTML = "Correct!";
    document.querySelector('#input').style.backgroundColor = 'green';
}

可选优化(规范代码)

全局变量a建议用const声明,避免意外修改和全局污染;判断相等时用===替代==,逻辑更严谨:

const a = "Aconcagua";
// ...
if (document.querySelector('#input').value.localeCompare(a) === 0)

完整修复代码

HTML 部分

<div class="wrapper">
    <div class="header">
        <h1>Trivia!</h1>
    </div>
    <div class="section">
        <h2>Part 2: Free Response</h2>
        <hr>
        <h3>What is the highest mountain in South America?</h3>
        <form action="" id="form">
            <input id="input" type="text">
            <button id="b" type="submit">Submit</button>
        </form>
    </div>
    <h2 id="2solution"></h2>
</div>

JavaScript 部分

function wrong2() {
    document.querySelector('#2solution').innerHTML = "Incorrect.";
    document.querySelector('#input').style.backgroundColor = 'red';
}
function right2() {
    document.querySelector('#2solution').innerHTML = "Correct!";
    document.querySelector('#input').style.backgroundColor = 'green';
}

const a = "Aconcagua";
document.querySelector('#form').addEventListener('submit', function(event){
    if (document.querySelector('#input').value.localeCompare(a) === 0) {
        right2();
    } else {
        wrong2();
    }
    event.preventDefault();
});

内容的提问来源于stack exchange,提问作者Santiago De Luca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:32:31