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

如何根据答题对错修改单选按钮文本颜色?现有代码能否实现?

实现答题结果文本颜色反馈(基于现有代码修改)

完全可以基于你现有的代码实现这个功能,不需要调整整体代码结构,只需要在判断选中选项的逻辑中,添加修改对应文本颜色的代码即可。

修改思路

  1. 定位对应文本元素:每个单选按钮都包裹在.answer容器中,通过选中的单选按钮的父元素,就能找到对应的<span class="answer-text">。
  2. 根据答案正确性设置颜色:
    • 选中值为"true"时,将文本颜色设为绿色
    • 选中值为"false"时,将文本颜色设为红色
  3. 可选优化:每次检查前重置所有答案文本的默认颜色,避免多次点击后颜色状态混乱。

修改后的完整JS代码

var result = 0;
function check() {
   result = 0; // 重置结果,避免多次累加
   var question;
   var choice;

   // 可选:重置所有答案文本的颜色为默认
   var allAnswerTexts = document.querySelectorAll('.answer-text');
   allAnswerTexts.forEach(text => {
      text.style.color = '';
   });

   for (question = 1; question <= 10; question++) {
      var q = document.forms['quiz'].elements['q'+question];
      // 原代码中未使用的rigth_anwswer变量可删除
      for (var i = 0; i < q.length; i++) {
         if (q[i].checked) {
            choice = q[i].value;
            // 获取对应答案文本的span元素
            var answerText = q[i].parentElement.querySelector('.answer-text');
            if (choice == "true") {
               result++;
               answerText.style.color = 'green';
            } else {
               answerText.style.color = 'red';
            }
         }
      }
   }
   alert(result);
}

额外提示

  • 你的HTML中存在拼写错误:Quastion应该是Question,JS里的rigth_anwswer是未使用的变量,建议修正以提升代码可读性。
  • 如果希望更优雅地管理样式,可以通过添加/移除CSS类来控制颜色,而不是直接修改行内样式:
    .correct { color: green; }
    .incorrect { color: red; }
    
    然后在JS中替换为:
    // 正确时
    answerText.classList.add('correct');
    answerText.classList.remove('incorrect');
    // 错误时
    answerText.classList.add('incorrect');
    answerText.classList.remove('correct');
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:55:54