我正在尝试学习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>
&#13;
答案 0 :(得分:0)
只需添加一个变量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>"
}