我正在写一个数字猜谜游戏。每次我运行文档时,它会自动转到我的外部声明,我知道原因,但我无法弄清楚如何让它等待文本框的输入值。我想设置"猜测" =按提交后输入文本框的值,然后输入if语句。此时它会自动设置为null并导致错误。这是代码。
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1><br>
<button onclick = "search(1,100)">Press to play!</button>
</body>
<script type="text/javascript">
var counter = 0;
var randomNumber = Math.floor(Math.random()*100+1);
function search(first, last){
document.open();
document.write("<h1>Number Guessing Game</h1><br>");
document.write("<input id = 'guessBox' type = 'text'> ");
document.write("<input type = 'submit' id = 'submit' value = 'Submit'><br>");
document.write("<h2>Numbers Left</h2>");
for(var i = first; i <= last; i++){
document.write(i + " ");
}
document.write("<br><br><h3>Number of tries: " + counter + "</h3>");
document.close();
var guess = document.getElementById('guessBox').value;
//var guess = prompt("Guess!");
myguess = parseInt(guess);
if(myguess <= last && myguess >= first && cont == true){
if(myguess == randomNumber){
counter++;
if(counter <=3){
alert("WOW, that was amazingly quick! You found it in " + counter + " tries.");
}
else if(counter < 6 && counter >= 4){
alert("Not bad! You found it in " + counter + " tries.");
}
else if(counter < 10 && counter >= 6){
alert("Ouch! You found it in " + counter + " tries.");
}
else{
alert("Having a bad day aren't you? You found it in "+ counter + " tries");
}
}
else if(myguess < randomNumber){
first = myguess+1;
alert("Try again! The number is higher.");
counter++;
search(first, last);
}
else{
last = myguess-1;
alert("Try again! The number is lower.");
counter++;
search(first, last);
}
}
else{
alert("Invalid Number, try again.");
search(first, last);
}
}
</script>
答案 0 :(得分:2)
您是否尝试禁用该按钮,然后在文本框中添加onChange事件,以便在获得所需输入后启用按钮?您需要在按钮中添加ID或Name值才能访问它?并添加@LGSon添加的内容:
if(myguess&lt; = last&amp;&amp; myguess&gt; = first&amp;&amp; cont == true){,你检查变量cont,我在你的代码中找不到,所以如果它是未声明并设置在某处,您的代码将始终采用外部路径。
其次,您需要将搜索功能拆分为2个函数,一个生成输入,一个在有人输入值时运行(可以在按键或按钮上触发)