[英]Javascript Local vs Global Variables
我正在嘗試學習Javascript,正在提出一個簡單的數學問題,並試圖創建一個對正確答案和錯誤答案進行評分的函數,但是我不知道如何從函數中傳遞任何信息來永久保持評分。 誰能幫我?
<html> <body> <p id="question"></p> <input id="answerBox" type=number> <button onclick="checkAnswer()">Answer</button> <p id="answer"></p> <p id="score"></p> <p id="newQuestion"></p> <script> //create MathAddition Problem; var mathAdd = function(x, y) { return x + " + " + y + " = " } //set random numbers; var x = Math.floor((Math.random()*10)+1); var y = Math.floor((Math.random()*10)+1); var z = x + y console.log(z) //Call mathAdd function; document.getElementById("question").innerHTML=mathAdd(x, y); //Check Answer var checkAnswer = function() { var answer=document.getElementById("answerBox").value; if(answer == z) { document.getElementById("answer").innerHTML=answer + " is correct"; document.getElementById("score").innerHTML="Your score is improving" ; } else { document.getElementById("answer").innerHTML=answer + " is not correct"; document.getElementById("score").innerHTML="Your score is dropping. Work harder!" ; } document.getElementById("newQuestion").innerHTML="<a href='test7.html'>Next Question</a>" } </script> </body> </html>
只需添加一個可變score
,每當答案正確時, score
就會增加。 像這樣:
var score = 0;
//Check Answer
var checkAnswer = function() {
var answer = document.getElementById("answerBox").value;
if (answer == z) {
score++;
document.getElementById("answer").innerHTML = answer + " is correct";
document.getElementById("score").innerHTML = "Your score increased to " + score;
}
else {
score--;
document.getElementById("answer").innerHTML = answer + " is not correct";
document.getElementById("score").innerHTML = "Your score dropped to " + score + ". Work harder!" ;
}
document.getElementById("newQuestion").innerHTML = "<a href='test7.html'>Next Question</a>"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.