我试图做一个猜数字游戏,它的正确输出应该逐行显示:尝试1你的猜测xx太小(大) 尝试2你的猜测xx太小了(大) 尝试2你的猜测xx太小了(大) ...
但我的输出总是在同一行改变,如下所示: 尝试3你的猜测xx太小了(大) 我不知道这个问题,请帮忙。
<html>
<head> <title> Guessing game </title>
</head>
<body onload="noGen()" >
<script type = "text/javascript">
var theNumber;
function noGen(){
theNumber= Math.floor(Math.random()*999+0) ; //get a random number
}
</script>
<h1> Guessing game </h1>
<p> You have 10 chances! </p>
<p>Hint: the number is between 0 and 999 </p>
<p id="myguess"> </p>
<p>
<input id="tryno" type="text" />
<input type="button" value="GUESS" onclick="attempt()" />
</p>
<script type= "text/javascript">
i=0;
function attempt(){
var guess=document.getElementById('tryno');
var myNumber=guess.value;
i++;
if(i<11)
{
if (myNumber<theNumber){
document.getElementById("myguess").innerHTML="Attempt "+i+" Your guess "+ myNumber+ " is too small";
}
else if (myNumber>theNumber)
{document.getElementById("myguess").innerHTML="Attempt "+i+" Your guess "+ myNumber+ " is too big";
}
else if (myNumber==theNumber){
document.getElementById("myguess").innerHTML="Attempt "+i+" Your guess "+ myNumber+ " is correct";
document.getElementById("info").innerHTML= "You win!";} }
else
{ document.getElementById("info").innerHTML= "You lose!";}
}
</script>
<p id="info"></p>
</body>
</html>
答案 0 :(得分:1)
如果您尝试保留以前的结果并继续在列表中添加,请尝试以下操作:
if (myNumber<theNumber){
var parSmall = document.createElement("P");
var ansSmall = document.createTextNode("\nAttempt "+i+" Your guess "+ myNumber+ " is too small");
parSmall.appendChild(ansSmall);
document.getElementById("myguess").appendChild(parSmall);
}
else if (myNumber>theNumber) {
var par = document.createElement("P");
var ans = document.createTextNode("\nAttempt "+i+" Your guess "+ myNumber+ " is too big");
par.appendChild(ans);
document.getElementById("myguess").appendChild(par);
编辑:innerHTML会更改div的内容,而这会将新的
元素和新文本添加到div中,以便获得:
<p> guess one
<p> guess two
<p> guess three
等