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

如何在JavaScript中为随机排序的测验选项添加正误值?

解决测验APP选项添加正误标识的问题

有两种简单的方法可以实现你的需求,同时保持选项排序不变:

方法一:渲染时直接判断正误(简洁版)

不用修改你现有的合并排序逻辑,只需要在map渲染环节,直接判断当前选项是否等于正确答案,生成对应的true/false值即可:

const correctAnswer = data[num].correctAnswer;
const incorrectAnswers = data[num].incorrectAnswers;
const combinedQuestions = [correctAnswer, ...incorrectAnswers].sort();

answerContainer.innerHTML = combinedQuestions.map((item, index) => `
  <li>
    <input type="radio" value="${item === correctAnswer}" id="answer-${index}" name="quiz-answer"/>
    <label for="answer-${index}">${item}</label>
  </li>
`).join('');

这里修正了两个关键细节:

  • 把所有单选按钮的name设为同一个值(比如quiz-answer),确保它们属于同一组,用户只能选中一个选项
  • 给id添加前缀(比如answer-${index}),避免和页面其他元素的id冲突,同时保证label与input的关联正确

方法二:包装成对象保留标识(清晰版)

如果需要更清晰的数据结构,可以先把每个选项包装成包含文本和正误状态的对象,再排序渲染,逻辑会更直观:

const correctAnswer = data[num].correctAnswer;
const incorrectAnswers = data[num].incorrectAnswers;

// 包装成带正误标识的对象数组
const answerItems = [
  { text: correctAnswer, isCorrect: true },
  ...incorrectAnswers.map(ans => ({ text: ans, isCorrect: false }))
];

// 按文本排序,和你之前的字符串排序结果完全一致
answerItems.sort((a, b) => a.text.localeCompare(b.text));

// 渲染时直接取isCorrect属性作为value
answerContainer.innerHTML = answerItems.map((item, index) => `
  <li>
    <input type="radio" value="${item.isCorrect}" id="answer-${index}" name="quiz-answer"/>
    <label for="answer-${index}">${item.text}</label>
  </li>
`).join('');

这两种方法都能在保持选项排序的同时,给每个输入框添加对应的正误值,后续你可以通过获取选中单选按钮的value来判断用户是否答对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:35:18