javascript - 在“onclick”事件上调用的函数是否等待函数结束?
问题描述
所以我想对html文档进行测验。一切都很好,直到我验证每个问题的答案是正确还是错误。
如果问题的答案是正确的,我想将答案(按钮文本)更改为绿色或红色。问题是我当时只显示 1 个问题,但颜色更新仅在下一个问题出现后进行。是不是因为文档更改只有在函数结束后才会发生?html代码很简单:
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if(this.getQuestionIndex().isCorrectAnswer(answer)) {
console.log(answer);
this.score++;
}
for(var i = 0; i < quiz.getQuestionIndex().choices.length; i++) {
var number =this.getQuestionIndex().getCorrectAnswer().charCodeAt(0)-65;
if (i===number)
document.getElementById("btn"+ i).style.color="green";
else
document.getElementById("btn"+ i).style.color="red";
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, textAnswer, choices, answer) {
this.text = text;
this.textAnswer = textAnswer;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
Question.prototype.getCorrectAnswer= function(){
return this.answer
}
function populate() {
if(quiz.isEnded()) {
showScores();
}
else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for(var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("1.Cum sunt semnalizate benzile de circulație reversibilă, care vă permit să continuați deplasarea?",
["A: cu dispozitive de culoare galbenă intermitentă",
"B: cu semnul roșu în cruce",
"C: cu semnalul verde de forma unei săgeți cu vârful în jos"],
["A", "B","C"],
"C"),
new Question("2.Precizați care dintre indicatoarele de mai jos indică o cale rutieră cu sens unic: <br> <img class='image' src='Test/7533.jpg' /> </br>",
["A: indicatorul 1",
"B: indicatorul 2",
"C: ambele indicatoare"],
["A", "B","C"],
"C"),
new Question("3.Ce semnifică indicatorul din imagine? <br> <img class='image' src='Test/3615.jpg' /> </br>",
["A: Accesul interzis copiilor neînsoțiți",
"B: Trecere obligatorie pentru copii",
"C: Copii"],
["A", "B","C"],
"C"),
new Question("4.Ce semnificație are un astfel de marcaj rutier? <br> <img class='image' src='Test/3687.jpg' /> </br>",
["A: marcaj pentru spații interzise",
"B: marcaj pe o bandă de decelerare",
"C: deviere temporară a circulației"],
["A", "B","C"],
"B"),
new Question("5.Ce semnificație are indicatorul din imagine? <br> <img class='image' src='Test/3659.jpg' /> </br>",
["A: urmează un sector de drum îngustat temporar",
"B: urmează o intersecție cu un drum fără prioritate",
"C: este interzisă schimbarea direcției de mers la dreapta în prima intersecție"],
["A", "B","C"],
"B"),
new Question("6.Ce semnificație are marcajul rutier din imagine? <br> <img class='image' src='Test/3589.jpg' /> </br>",
["A: spațiu pentru oprirea în caz de urgență",
"B: marcaj transversal de oprire",
"C: bandă de circulație destinată opririi voluntare"],
["A", "B","C"],
"B"),
new Question("7.Ce obligații revin conducătorilor la întâlnirea indicatorului? <br> <img class='image' src='Test/3438.jpg' /> </br>",
["A: să acorde prioritate vehiculelor care circulă în intersecție",
"B: să acorde prioritate de dreapta",
"C: să ocolească centrul intersecției și să circule cât mai aproape de marginea străzii"],
["A", "B","C"],
"A"),
new Question("8.Care este semnificația indicatorului? <br> <img class='image' src='Test/3601.jpg' /> </br>",
["A: obligă la ocolirea prin dreapta a locului unde este instalat",
"B: obligă la schimbarea direcției de mers către dreapta",
"C: obligă la folosirea benzii de lângă trotuar"],
["A", "B","C"],
"A"),
new Question("9.Indicatorul alăturat reprezintă: <br> <img class='image' src='Test/9509.jpg' /> </br>",
["A: panouri succesive pentru curbe deosebit de periculoase",
"B: panou suplimentar, montat la 150 m față de calea ferată",
"C: baliză bidirecțională care indică ocolirea obstacolului prin stânga sau prin dreapta"],
["A", "B","C"],
"C"),
new Question("10.Cum vei proceda la întâlnirea indicatorului „Limitare de viteză 80 km/h”? <br> <img class='image' src='Test/3615.jpg' /> </br>",
["A: nu depășești viteza maximă admisă pe drumurile naționale",
"B: nu depășești viteza de 80 km/h",
"C: circuli cu o viteză de peste 80 km/h"],
["A", "B","C"],
"B")
];
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<ul class="grid1">
<li id="textAnswer0"></li>
<li id="textAnswer1"></li>
<li id="textAnswer2"></li>
</ul>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
</div>
<span id="wrong_answer"></span>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>
我想要的是每次单击 AB 或 C 中的任何一个以显示哪个是错误/正确的,等待 3 秒然后转到下一个问题。
解决方案
您的代码没有与 javascript 的特殊性相关的问题,而是您调用函数的代码,以在您揭示答案的同一函数中显示下一个问题
当您向用户展示当前问题的答案时,您需要添加某种方式来导航到下一个问题
我为此添加<button onclick="populate();" id="nxtbtn">Next</button>
了
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if(this.getQuestionIndex().isCorrectAnswer(answer)) {
console.log(answer);
this.score++;
}
for(var i = 0; i < quiz.getQuestionIndex().choices.length; i++) {
var number =this.getQuestionIndex().getCorrectAnswer().charCodeAt(0)-65;
if (i===number)
document.getElementById("btn"+ i).style.color="green";
else
document.getElementById("btn"+ i).style.color="red";
}
this.questionIndex++;
document.getElementById('nxtbtn').disabled = false;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, textAnswer, choices, answer) {
this.text = text;
this.textAnswer = textAnswer;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
Question.prototype.getCorrectAnswer= function(){
return this.answer
}
function populate() {
if(quiz.isEnded()) {
document.getElementById('nxtbtn').style.display = 'none';
showScores();
}
else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show textAnswer
var textAnswer = quiz.getQuestionIndex().textAnswer;
for(var i = 0; i < textAnswer.length; i++) {
var element = document.getElementById("textAnswer" + i);
element.innerHTML = textAnswer[i];
}
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
for(var i = 0; i < quiz.getQuestionIndex().choices.length; i++) {
document.getElementById("btn"+ i).style.color="inherit";
}
document.getElementById('nxtbtn').disabled = true;
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("1.Cum sunt semnalizate benzile de circulație reversibilă, care vă permit să continuați deplasarea?",
["A: cu dispozitive de culoare galbenă intermitentă",
"B: cu semnul roșu în cruce",
"C: cu semnalul verde de forma unei săgeți cu vârful în jos"],
["A", "B","C"],
"C"),
new Question("2.Precizați care dintre indicatoarele de mai jos indică o cale rutieră cu sens unic: <br> <img class='image' src='Test/7533.jpg' /> </br>",
["A: indicatorul 1",
"B: indicatorul 2",
"C: ambele indicatoare"],
["A", "B","C"],
"C"),
new Question("3.Ce semnifică indicatorul din imagine? <br> <img class='image' src='Test/3615.jpg' /> </br>",
["A: Accesul interzis copiilor neînsoțiți",
"B: Trecere obligatorie pentru copii",
"C: Copii"],
["A", "B","C"],
"C"),
new Question("4.Ce semnificație are un astfel de marcaj rutier? <br> <img class='image' src='Test/3687.jpg' /> </br>",
["A: marcaj pentru spații interzise",
"B: marcaj pe o bandă de decelerare",
"C: deviere temporară a circulației"],
["A", "B","C"],
"B"),
new Question("5.Ce semnificație are indicatorul din imagine? <br> <img class='image' src='Test/3659.jpg' /> </br>",
["A: urmează un sector de drum îngustat temporar",
"B: urmează o intersecție cu un drum fără prioritate",
"C: este interzisă schimbarea direcției de mers la dreapta în prima intersecție"],
["A", "B","C"],
"B"),
new Question("6.Ce semnificație are marcajul rutier din imagine? <br> <img class='image' src='Test/3589.jpg' /> </br>",
["A: spațiu pentru oprirea în caz de urgență",
"B: marcaj transversal de oprire",
"C: bandă de circulație destinată opririi voluntare"],
["A", "B","C"],
"B"),
new Question("7.Ce obligații revin conducătorilor la întâlnirea indicatorului? <br> <img class='image' src='Test/3438.jpg' /> </br>",
["A: să acorde prioritate vehiculelor care circulă în intersecție",
"B: să acorde prioritate de dreapta",
"C: să ocolească centrul intersecției și să circule cât mai aproape de marginea străzii"],
["A", "B","C"],
"A"),
new Question("8.Care este semnificația indicatorului? <br> <img class='image' src='Test/3601.jpg' /> </br>",
["A: obligă la ocolirea prin dreapta a locului unde este instalat",
"B: obligă la schimbarea direcției de mers către dreapta",
"C: obligă la folosirea benzii de lângă trotuar"],
["A", "B","C"],
"A"),
new Question("9.Indicatorul alăturat reprezintă: <br> <img class='image' src='Test/9509.jpg' /> </br>",
["A: panouri succesive pentru curbe deosebit de periculoase",
"B: panou suplimentar, montat la 150 m față de calea ferată",
"C: baliză bidirecțională care indică ocolirea obstacolului prin stânga sau prin dreapta"],
["A", "B","C"],
"C"),
new Question("10.Cum vei proceda la întâlnirea indicatorului „Limitare de viteză 80 km/h”? <br> <img class='image' src='Test/3615.jpg' /> </br>",
["A: nu depășești viteza maximă admisă pe drumurile naționale",
"B: nu depășești viteza de 80 km/h",
"C: circuli cu o viteză de peste 80 km/h"],
["A", "B","C"],
"B")
];
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="grid">
<div id="quiz">
<h1>Quiz</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<ul class="grid1">
<li id="textAnswer0"></li>
<li id="textAnswer1"></li>
<li id="textAnswer2"></li>
</ul>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
</div>
<div>
<button onclick="populate();" id="nxtbtn">Next</button>
</div>
<span id="wrong_answer"></span>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>
推荐阅读
- .net - Dotnet core-如何从 IQueryable 获取选择器字符串?
- c# - SIMD指令集有宏吗?
- react-native - 如何在 react-native 中获得正确的 ColorScheme?
- python - 如何以字典方式逐项比较两个二维数组?
- android - 在 PainterSVG 中,如何将 Q 段或 C 段转换回 L 段?
- flutter - 颤动中的透明文本字段
- android - PayTM UPI 意图集成 - 系统错误
- node.js - 如何测试单个脚本对网站的性能影响?
- jquery - 如何将每行的删除按钮添加到 Jquery DataTable
- html - 系统暗/亮模式图标