添加两个随机数并将总和与用户输入进行比较时,比较始终为false

时间:2017-01-21 18:28:39

标签: javascript html random input addition

我要做的是随机化并为变量分配两个数字,并在向用户显示变量时添加它们。用户输入两个变量的总和,如果输入和总和相同,则用户获胜。但是,当我比较时,当我使用console.log查看布尔值时,结果始终为false。 我使用的是HTML和JavaScript。这是我的代码:

<html>
<head>
<title>
Game A
</title>
<script>
var y = parseInt(Math.floor(Math.random()*20));
var z = parseInt(Math.floor(Math.random()*20));
function myFunction() {
var p = parseInt(document.getElementById("demo"));
var z = parseInt(p);
var x = parseInt(y) + parseInt(z);
var q = parseInt(x);
console.log(z===q?true:false);
if(z===q){
alert("Good job!");
}
else{
alert("aw, try again!");
}
}
</script>
</head>
<body>
<p>Click the button to calculate x.</p>
<br/>
<div id="a" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('a').innerHTML= y;
</script>
</div>
<div id="b" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('b').innerHTML= z;
</script>
</div>
<input id="demo"></input>
<button onclick="myFunction()">Try it</button>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要使用:document.getElementById("demo").value从输入字段中获取值。不要通过重新分配新值来更改函数内z的值。请尝试:

&#13;
&#13;
<html>
<head>
<title>
Game A
</title>
<script>
var y = parseInt(Math.floor(Math.random()*20));
var z = parseInt(Math.floor(Math.random()*20));
function myFunction() {
var p = parseInt(document.getElementById("demo").value);
var z1 = parseInt(p);
var x = parseInt(y) + parseInt(z);
var q = parseInt(x);
  console.log(q); console.log(z1);
console.log(z===q?true:false);
if(z1===q){
alert("Good job!");
}
else{
alert("aw, try again!");
}
}
</script>
</head>
<body>
<p>Click the button to calculate x.</p>
<br/>
<div id="a" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('a').innerHTML= y;
</script>
</div>
<div id="b" style="display:inline-block;heigh:100px;width:100px;">
<script>
document.getElementById('b').innerHTML= z;
</script>
</div>
<input id="demo"></input>
<button onclick="myFunction()">Try it</button>

</body>
</html>
&#13;
&#13;
&#13;