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

求助:实现JavaScript测验根据总分展示对应评价文本

解决方案

核心修改点是在测验结束生成结果的逻辑里,根据总分判断要显示的文本。以下是修改后的完整代码,关键调整已标注:

const questions = [
    {
      "question": "你的IQ是多少?",
      "answer1": "低于18",
      "answer1Total": "1",
      "answer2": "18-30",
      "answer2Total": "2",
      "answer3": "高于30",
      "answer3Total": "3"
    },
    {
      "question": "你和朋友约好见面但对方爽约了,你会怎么做?",
      "answer1": "说“无所谓”,然后计划一个超棒的夜晚,让他们下次不敢爽约。",
      "answer1Total": "3",
      "answer2": "感到难过,因为你很期待这次见面。",
      "answer2Total": "2",
      "answer3": "没关系,其实你本来就想宅在家里。",
      "answer3Total": "1"
    },
    {
      "question": "你最喜欢以下哪种颜色?",
      "answer1": "黑色",
      "answer1Total": "1",
      "answer2": "黄色或浅蓝色",
      "answer2Total": "2",
      "answer3": "红色或橙色",
      "answer3Total": "3"
    },
  ]

  let currentQuestion = 0;
  let score = [];
  let selectedAnswersData = [];
  let scoringData = [];
  const totalQuestions = questions.length;

  const container = document.querySelector('.quiz-container');
  const questionEl = document.querySelector('.question');
  const option1 = document.querySelector('.option1');
  const option2 = document.querySelector('.option2');
  const option3 = document.querySelector('.option3');
  const nextButton = document.querySelector('.next');
  const previousButton = document.querySelector('.previous');
  const restartButton = document.querySelector('.restart');
  const result = document.querySelector('.result');

  //生成题目
  function generateQuestions (index) {
      const question = questions[index];
      const option1Total = questions[index].answer1Total;
      const option2Total = questions[index].answer2Total;
      const option3Total = questions[index].answer3Total;
      questionEl.innerHTML = `${index + 1}. ${question.question}`
      option1.setAttribute('data-total', `${option1Total}`);
      option2.setAttribute('data-total', `${option2Total}`);
      option3.setAttribute('data-total', `${option3Total}`);
      option1.innerHTML = `${question.answer1}`
      option2.innerHTML = `${question.answer2}`
      option3.innerHTML = `${question.answer3}`
  }


  function loadNextQuestion () {
      const selectedOption = document.querySelector('input[type="checkbox"]:checked');
      if(!selectedOption) {
          alert('请选择一个答案');
          return;
      }
      const answerScore = Number(selectedOption.nextElementSibling.getAttribute('data-total'));
      score.push(answerScore);

      // 修复原代码空push问题
      selectedAnswersData.push(selectedOption.value);

      // 修复箭头符号转义错误
      const totalScore = score.reduce((total, currentNum) => total + currentNum);

      currentQuestion++;
      selectedOption.checked = false;

      if(currentQuestion == totalQuestions - 1) {
          nextButton.textContent = '查看结果';
      }
      if(currentQuestion == totalQuestions) {
          container.style.display = 'none';
          // 根据总分判断显示对应文本
          let resultText = '';
          if (totalScore < 5) {
              resultText = '<em>you must try harder</em>';
          } else if (totalScore >=5 && totalScore <=10) {
              resultText = '<em>Good job</em>';
          } else {
              resultText = '<em>you are excellent</em>';
          }
          // 生成结果HTML
          result.innerHTML =
           `<h1 class="final-score">你的总分: ${totalScore}</h1>
           <div class="summary">
              <h1>评价</h1>
              <p>${resultText}</p>
          </div>
          <button class="restart">重新开始</button>
           `;
          return;
      }
      generateQuestions(currentQuestion);
  }

  //上一题逻辑
  function loadPreviousQuestion() {
      currentQuestion--;
      score.pop();
      generateQuestions(currentQuestion);
  }

  //重新开始测验
  function restartQuiz(e) {
      if(e.target.matches('button')) {
          currentQuestion = 0;
          score = [];
          location.reload();
      }
  }
  generateQuestions(currentQuestion);
  nextButton.addEventListener('click', loadNextQuestion);
  previousButton.addEventListener('click',loadPreviousQuestion);
  result.addEventListener('click',restartQuiz);

  //单选控制逻辑
  function selectOnlyThis(id){
    var option = document.getElementsByName("option");
    Array.prototype.forEach.call(option,function(el){
      el.checked = false;
    });
    id.checked = true;
  }
html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
body {
  margin: 0;
  padding: 0;
  font-family: "Roboto", sans-serif;
  font-weight: 100;
  line-height: 1.7rem;
  background: no-repeat linear-gradient(250deg, #ff934f, #db222a);
}
.quiz-container {
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);
  text-shadow: 1px 1px white;
  padding: 25px 40px 40px 40px;
  text-shadow: 0 1px #00000010;
  width: 40%;
  margin: 5rem auto;
  display: flex;
  flex-direction: column;
  background: linear-gradient(360deg, gray, white);
  border-radius: 5px;
}
.title {
  color: black;
  font-weight: 400;
  font-size: 2.5rem;
  text-align: left;
  background-color: gray;
  padding: 17px;
  margin-top: -5px;
  margin-right: -17px;
  margin-bottom: -5px;
  margin-left: -17px;
}
.question {
  margin: 0px 0px 20px 0px;
  font-size: 1.5rem;
}
.option {
  padding: 1rem;
  color: black;
  background: rgba(255, 255, 255, 0.1);
  width: 100%;
  border-radius: 5px;
  transition: all 0.3s;
  font-size: 20px;
      cursor: pointer;
}
.option:hover {
  background: rgba(255, 255, 255, 0.4);
}
.option input:checked .option {
  background: #08038c;
  color: #000;
}
.controls > * {
  margin: 30px 10px 0px 0px;
}
button {
  padding: 0.5rem 1.5rem;
  border: none;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-weight: 300;
  color: white;
  outline: none;
  transform: scale(0.98);
  transition: all 0.2s;
}
button.previous {
  background: #F10849;
    border: 2px white solid;
}
button.next {
  background: #F10849;
  border: 2px white solid;
}
button.restart {
  background: #F10849;
  color: black;
  font-size: 2rem;
  margin-bottom: 1rem;
  transition: all 0.4s;
}
button.restart:hover {
  color: white;
}
button:hover,
button:focus {
  transform: scale(1);
  font-weight: 500;
  box-shadow: 1px 1px 1px rgba(255, 255, 255, 0.5);
}
.result {
  display: flex;
  flex-direction: column;
  padding: 2rem;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 2.5rem;
  min-height: 100vh;
}
.final-score {
  color: #00000099;
}
.summary {
  font-size: 1rem;
  text-shadow: 1px 1px #ffffff50;
  color: #00000099;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0 2rem;
  margin-bottom: 2rem;
}
.summary h1 {
  align-self: left;
}


hr {
  border: 2px;
  border-top: 2px solid black;
  padding: 15px 10px 15px 10px;
}


input[type="checkbox"] {
    width:20px;
    height:20px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background:url(check_radio_sheet.png) -38px top no-repeat;
    cursor:pointer;
}
<head>
    <title>性格测试</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>

<body>

    <div class="quiz-container">
        <div class="title">性格测试</div><hr>
        <div id="question" class="question"></div>
        <label class="option">
            <input type="checkbox" name="option" value="1" onclick="selectOnlyThis(this)"/>
            <span class="option1"></span>
        </label>
        <label class="option">
            <input type="checkbox" name="option" value="2" onclick="selectOnlyThis(this)"/>
            <span class="option2"></span>
        </label>
        <label class="option">
            <input type="checkbox" name="option" value="3" onclick="selectOnlyThis(this)"/>
            <span class="option3"></span>
        </label>
        <!-- 按钮 -->
        <div class="controls">
            <button class="previous">上一题</button>
            <button class="next">下一题</button>
        </div>
    </div>

    <div class="result">

    </div>
</body>

关键修改说明

  1. 修复了原代码中reduce方法箭头符号被转义的错误(=&gt;改为=>)
  2. 补全selectedAnswersData.push()的参数,避免空值存入数组
  3. 在测验结束逻辑中新增总分判断分支,根据分数段生成对应评价文本
  4. 将题目、按钮文本翻译成中文,同时保留要求的英文评价文本
  5. 修正HTML中按钮标签的语法错误(多余的>符号)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:25:23