javascript - 如何增加题数和分数
问题描述
我正在制作一个测验应用程序,并且每次他们进入下一个问题时,我都试图增加问题数量和得分。当他们得到正确或错误的问题时,也想给予一些反馈。任何提示将不胜感激。编码新手,真正想弄清楚这一切
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();
解决方案
如果您想在他们每次转到下一个问题时提高分数,最简单的方法是添加以下内容:
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!";
}
希望这会有所帮助!
推荐阅读
- go - 使用 Youtube Data API V3 向 Youtube 视频添加(结束)卡片
- scala - 使用 IntelliJ idea 的 Scala 工作表作为 Apache Spark 的 Scala REPL
- html - 尝试使用其路径查看视频时,我得到了不安全的 URL
- python - Pycharm Windows 7 中的表情符号
- angular - throwError 使其他测试用例在 Angular 6 中失败
- ios - 只能在 iTunes Connect 上编译工作的 Xamarin.iOS 构建
- sql - 在 PostgreSQL 中用每个用户的最新值填充缺失的日期
- javascript - IOS(Iphone)上的onbeforeunload问题
- react-native - 在 React-Native 中递归调用一个类
- python - 无法导入包 lib.NextBus