首页 > 解决方案 > 如何增加题数和分数

问题描述

我正在制作一个测验应用程序,并且每次他们进入下一个问题时,我都试图增加问题数量和得分。当他们得到正确或错误的问题时,也想给予一些反馈。任何提示将不胜感激。编码新手,真正想弄清楚这一切

let currentQuestion = 0;

let score = 1;

function renderQuestion() {

document.getElementById("quiz").innerHTML =
`
     <fieldset>
     <legend> ${questions[currentQuestion].question} </legend>
     <input  type="radio" name="option" 
     value="A">${questions[currentQuestion].options[0].option}<br>
     <input type="radio" name="option" 
     value="B">${questions[currentQuestion].options[1].option}<br>
     <input type="radio" name="option" 
     value="C">${questions[currentQuestion].options[2].option}<br>
     <input type="radio" name="option" 
     value="D">${questions[currentQuestion].options[3].option}<br>
     <button id="button" class="submitAnswer"> Submit answer </button>
     <div id="errorMessage">
     </div>
     <div id="feed">
      </div>
    </fieldset>

    `;

    document.getElementById("button").addEventListener("click", 
  function(event) {

    event.preventDefault();

    let hasAnswer = false;

    for (let el of document.querySelectorAll("input")) {

        if (el.checked) {

            hasAnswer = true;

            if (el.value === questions[currentQuestion].answer)


    {

                score++;
            }
        }
    }

    if (hasAnswer) {

        if (currentQuestion === questions.length - 1) {

            document.getElementById("quiz").innerHTML = `Your score is 
   ${score}`;
        }

        else {
            currentQuestion++;
            renderQuestion();
        }
    }
      else {
        document.getElementById("errorMessage").innerHTML = "Please 
select an answer!";

    }
  });
 }



renderQuestion();

标签: javascriptjqueryhtmlcss

解决方案


如果您想在他们每次转到下一个问题时提高分数,最简单的方法是添加以下内容:

score++;

在这里面:

else {
    currentQuestion++;
    score++;
    renderQuestion();
}

这是在这个块内:

if (hasAnswer) {

        if (currentQuestion === questions.length - 1) {

            document.getElementById("quiz").innerHTML = `Your score is 
   ${score}`;
        }

        else {
            currentQuestion++;
            score++;
            renderQuestion();
        }
    }
      else {
        document.getElementById("errorMessage").innerHTML = "Please 
select an answer!";

    }

希望这会有所帮助!


推荐阅读