【发布时间】:2021-07-13 22:56:51
【问题描述】:
我正在尝试使用 JavaScript 和 html 进行测验。要求用户在提示字段中输入问题的答案,用户回答并将正确答案发送到比较它们的功能。如果减去正确答案的答案等于 0,该函数将返回一个点。如果不是这样,该函数将不会返回一个点。如果用户的回答不是 1-3,则函数会提示输入无效。这里的一切都有效,但是我想添加一个功能,如果用户的回答无效,也就是不是 1-3,让代码再次询问相同的问题。 我试过使用 while 循环,但不能让它工作。关于如何解决这个问题的任何建议和/或任何其他使代码更有条理的提示。
<!DOCTYPE HTML>
<HTML>
<HEAD>
<META CHARSET="UTF-8">
<TITLE>Quiz</TITLE>
</HEAD>
<BODY>
<SCRIPT TYPE="text/javascript">
var points = 0;
var answer = parseInt(prompt("Which animal is not a mammal? \n 1. Shark \n 2. Dolphin \n 3. Whale"));
correctanswer = 1;
control(answer, correctanswer);
answer = parseInt(prompt("Which country is not in asia? \n 1. Georgia \n 2. Ukraine \n 3. Iran"));
correctanswer = 2;
control(answer, correctanswer);
answer = parseInt(prompt("What is amazons founder named? \n 1. Jeff Bezos \n 2. Kenneth Spielberg \n 3. Elon Musk"));
correctanswer = 1;
control(answer, correctanswer);
answer = parseInt(prompt("Which element are diamonds made of? \n 1. Platinum \n 2. Iron \n 3. Carbon"));
correctanswer = 3;
control(answer, correctanswer);
answer = parseInt(prompt("Which gases make up the biggest part of the atmosphere? \n 1. Oxygen and carbondioxide \n 2. Nitrogen and oxygen \n 3. Oxygen and hydrogen"));
correctanswer = 2;
control(answer, correctanswer);
answer = parseInt(prompt("Which country is not in the EU? \n 1. Lithuania \n 2. Croatia \n 3. Bosnia"));
correctanswer = 3;
control(answer, correctanswer);
function control(answer, correctanswer) {
if(answer < 1 || answer > 3 || isNaN(answer)) {
alert("Invalid input! Try again!");
}
else if((answer - correctanswer) == 0) {
return points += 1;
}
}
document.write("You got: " + points + " total points of 6 .")
</SCRIPT>
</BODY>
</HTML>
【问题讨论】:
-
我在您的代码中没有看到任何
while。请说明您尝试了什么以及遇到了什么问题。
标签: javascript html while-loop prompt