Javascript警报不会解雇(while循环)

时间:2015-06-11 14:55:43

标签: javascript html while-loop

我试图制作一个"你举起几个手指"页面,如果我在框中输入1-5,它可以工作,但如果我输入超过5,警报不会消失,任何人都可以帮助我吗?抱歉,这个菜鸟问题 任何帮助将不胜感激!谢谢!



document.getElementById("guess").onclick = function() {

  var gotIt = false;
  var guesess = 1;
  var x;

  while (gotIt == false) {
    x = Math.random();
    x = 6 * x;
    x = Math.floor(x);

    if (document.getElementById("myNumber").value == x) {
      gotIt = true;
    } else {
      if (guesess == 20) {
        alert("i give up");
      } else {
        guesses++;
      }
    }
  }
  alert("I got it! It was a " + x + "It only took me " + guesess + "guesses");
}

<p>How many fingers are you holding up?</p>
<input id="myNumber" />
<button id="guess">Guess!!</button>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

第一个问题,修复您的拼写错误:您使用guesessguesses混合使用它们必须全部相同。

第二个问题,一旦代码'放弃',它就不会设置标志来打破循环。您可以在警报后使用break来打破循环:

alert("i give up");
break;

第三个问题,如果找不到匹配项(即gotIt仍为假),您需要检查以确保不显示“我收到”消息:

if (gotIt) 
    alert("I got it! It was a " + x + "It only took me " + guesess + "guesses");

(或者您可以将此警报放在设置gotIt = true

的同一个if块中

Here is a working example

答案 1 :(得分:0)

最好转换你的输入 您可以尝试替换您的java脚本代码,以便控制转换问题,并放置

alert("I got it! It was a " + x + " It only took me " + guesess + "guesses");

在if(x == n)内,因为当随机数与输入键控匹配时,警报将弹出 试试这段代码:

document.getElementById("guess").onclick = function() {
  var gotIt = false;
  var guesess = 1;
  var x;
  var num=parseInt(document.getElementById('myNumber').value);

  while (gotIt == false) {
    x = Math.random();
    x = 6 * x;
    x = Math.floor(x);

    if (x == num) {
      gotIt = true;
        alert("I got it! It was a " + x + " It only took me " + guesess + "guesses");
    } else {
      if (guesess == 20) {
        alert("i give up");
          break;
      } else {
        guesess++;
      }
    }
  }

}