繁体   English   中英

Javascript局部变量与全局变量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM