我正在尝试创建一个简单的猜谜游戏,我的返回值或我的功能似乎是正确的。我有我的输入值的console.logged typeof以及我的randNum值,它们都是数字。但是我的警报始终不正确。我做错了什么?
var currentGuess = false;
var randNum = Math.floor(Math.random() * 100)
var input = document.getElementById("guess").value;
var input = parseInt(input);
var btn = document.getElementById("submit");
var results = document.getElementById("results");
console.log(randNum);
function check() {
checkNum(input, randNum);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
function checkNum(guess, actualNum) {
currentGuess = false;
if(guess === actualNum) {
return true;
}
return currentGuess;
}
btn.addEventListener("click", check, false);
答案 0 :(得分:2)
调用支票时,您没有再次接受输入。
只需在检查功能
中添加input = parseInt(document.getElementById("guess").value);
喜欢这个
function check() {
input = parseInt(document.getElementById("guess").value);
checkNum(input, randNum);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
答案 1 :(得分:-1)
摆弄工作解决方案:https://jsfiddle.net/pp9Lrpe6/
你正在监听输入上的点击,但是在加载所有内容时获取输入值,这是空的 - 返回input = NaN。当用户点击时,该值不会更新:
var randNum, btn, results;
// Generate random number.
randNum = Math.floor( Math.random() * 100 );
// Submit button to listen for click events on.
btn = document.getElementById( 'submit' );
// Display result one at a time in #results.
results = document.getElementById( 'results' );
// Number to guess.
console.log( 'Random number: ' + randNum );
// Check the input on click of #submit
function check() {
var input = parseInt( document.getElementById( 'guess' ).value, 10 );
if ( input === randNum ) {
results.innerHTML = '<p class="correct">' + input + ' is correct!</p>';
} else {
results.innerHTML = '<p class="incorrect">' + input + ' is not correct!</p>';
}
}
// Add event listener for #submit
btn.addEventListener( 'click', check, false );
作为一种好习惯,你应该输入type =&#34; number&#34;。 您还应该为parseInt(MDN)
声明基数答案 2 :(得分:-1)
试试这个:
<html>
<head>
</head>
<body>
<input type="text" id="guess"><br>
<input type="button" id="submit" value="check"><br>
<div id="results"></div>
<script>
var currentGuess = false;
var randNum = Math.floor(Math.random() * 100)
var btn = document.getElementById("submit");
var results = document.getElementById("results");
console.log(randNum);
function check() {
var input = document.getElementById("guess").value;
var input = parseInt(input);
if( input === randNum) {
alert("correct");
} else {
alert("incorrect");
}
}
btn.addEventListener("click", check, false);
</script>
</body>