所以这是程序:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<input type="number" id="myNumber" value="">
<button onclick="Kaas()">Controleer</button>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<script>
var z= 0;
function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo2").innerHTML = y;
var z = x-y
document.getElementById("demo3").innerHTML = z;
}
var a=0;
function Kaas() {
var x = document.getElementById("myNumber").value;
if(x==z){
document.getElementById("demo4").innerHTML = "Correct";
}else{
if(a==3){
document.getElementById("demo4").innerHTML = "Fout, het goede antwoord is" + z;
}else{
document.getElementById("demo4").innerHTML = "Fout, probeer het nog een keer";
a +=1;
}
}
}
</script>
</body>
</html>
&#13;
但它不起作用。我试图做到这一点,所以我输入正确的答案然后它会说正确或不正确。
此外,我想让它在3次后说出正确的答案。
答案 0 :(得分:1)
您正在将z
变量重新定义为本地变量。外面从未改变过。
只需在功能中var
之前删除z
:
var z= 0;
function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
var y = Math.floor((Math.random() * 10) + 1);
z = x - y;
document.getElementById("demo").innerHTML = x;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo3").innerHTML = z;
}
var a=0;
function Kaas() {
var x = document.getElementById("myNumber").value;
if (x==z) {
document.getElementById("demo4").innerHTML = "Correct";
} else {
if (a==3) {
document.getElementById("demo4").innerHTML = "Fout, het goede antwoord is" + z;
} else {
document.getElementById("demo4").innerHTML = "Fout, probeer het nog een keer";
a += 1;
}
}
}
<button onclick="myFunction()">Try it</button>
<input type="number" id="myNumber" value="">
<button onclick="Kaas()">Controleer</button>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>