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

如何让测验的正确答案按钮随机出现在四个预设位置中的任意一个?

测验脚本选项随机排序实现方案

你可以直接使用修改后的完整代码,核心实现了正确答案按钮随机排列的需求,同时修复了原代码的语法错误:

完整HTML代码

<button id="start" onclick="start()">start test</button>
<div id="question"></div>
<br>
<!-- 新增选项容器,用来动态插入打乱顺序的按钮 -->
<div id="options-container"></div>
<br>
<div id="answerstatus"></div>

<!-- 选项按钮默认隐藏,后续动态插入到容器中 -->
<button style="display:none;" id="correctanswer" onclick="shownextquestion();correct()">Correct Answer</button>
<button style="display:none;" id="wronganswer1" onclick="shownextquestion();incorrect()">Wrong Answer</button>
<button style="display:none;" id="wronganswer2" onclick="shownextquestion();incorrect()">Wrong Answer</button>
<button style="display:none;" id="wronganswer3" onclick="shownextquestion();incorrect()">Wrong Answer</button>

完整JavaScript代码

const questions = [
  {name: "question1"}, 
  {name: "question2"}, 
  {name: "question3"}
];
// 存储所有选项按钮节点
const optionButtons = [
  document.getElementById("correctanswer"),
  document.getElementById("wronganswer1"),
  document.getElementById("wronganswer2"),
  document.getElementById("wronganswer3")
];
const optionsContainer = document.getElementById("options-container");

// 通用打乱数组函数
function shuffle(arr) {
  let currentIndex = arr.length, randomIndex;
  while (currentIndex != 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [arr[currentIndex], arr[randomIndex]] = [arr[randomIndex], arr[currentIndex]];
  }
  return arr;
}

// 随机排列选项按钮
function renderRandomOptions() {
  // 打乱选项按钮数组
  const shuffledOptions = shuffle([...optionButtons]);
  // 清空容器后插入打乱后的按钮
  optionsContainer.innerHTML = '';
  shuffledOptions.forEach(btn => {
    // 每个按钮后面加换行,和原布局保持一致
    optionsContainer.appendChild(btn);
    optionsContainer.appendChild(document.createElement('br'));
  });
}

function start() {
  document.getElementById("start").style.display = "none";
  shuffle(questions);
  document.getElementById("question").innerHTML = questions[0].name;
  // 显示所有选项按钮
  optionButtons.forEach(btn => btn.style.display = "block");
  // 渲染随机排序的选项
  renderRandomOptions();
}

function shownextquestion() {
  shuffle(questions);
  document.getElementById("question").innerHTML = questions[0].name;
  // 每道题都重新打乱选项顺序
  renderRandomOptions();
}

function correct() {
  // 修复原代码遗漏innerHTML的语法错误
  document.getElementById("answerstatus").innerHTML = "Correct Answer!";
}

function incorrect() {
  document.getElementById("answerstatus").innerHTML = "Wrong Answer";
}

核心改动说明

  • 新增options-container作为选项按钮的父容器,所有按钮动态插入该容器实现顺序调整
  • 复用你原有的打乱算法,新增选项按钮打乱逻辑,每次加载题目时都会重新随机排列4个选项的位置
  • 修复了原代码中给答题状态文本赋值时缺失innerHTML的语法错误
  • 保留了你原有的所有业务逻辑和按钮事件绑定,不需要调整原有交互逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:15:04