无法弄清楚这段代码中有什么不对

时间:2016-12-17 07:22:20

标签: javascript html html5 while-loop

我是编程新手。我学到了一些JavaScript,然后我编写了代码。一切都是真的,一切都很好,但是当它是假的时候我需要添加一些东西。所以我添加了一个while,但这对我没用。有人可以帮帮我吗?谢谢你的答案!

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8"/>
    <link rel="stylesheet" href="styles.css"/>
    <script src="JavaScript.js"></script>
    <title>
      Hello
    </title>
  </head>
  <body>
    <p id="Hello"></p>
    <script>
      function onload() {
      alert("choose a number between 1 and 9");
      var Multiply1 = prompt("Multiply this number by 9");
      
      while (Multiply1 % 9 != 0) {
      alert("This can't be true");
      var Multiply = prompt("Multiply this number by 9");
      }
      
      while (multiply1 % 9 = 0) {
      var add = prompt("Add the 2 digits you have");
      }
      
      while (add != 9) {
      alert("This can't be true");
      var add1 = prompt("Add the 2 digits you have");
      }
      
      while (add = 9) {
      var decrease = prompt("deacrease the number you have chosen from the number you got:");
      alert("the number you have chosen is " + (9-decrease));
      
      }
      }
      
    </script>
    <noscript>Please enable JS</noscript>
    <button onclick="onload()">Cilck on me to start"</button>
  </body>
</html>

3 个答案:

答案 0 :(得分:0)

我看到一些问题 - 首先是Javascript区分大小写,因此您需要使用变量的确切大小写 - Multiply1 != multiply1。接下来的是,只要条件为真,while循环就会继续,因此您将被卡在最先评估为true的循环中。相反,你应该有一个内部if条件的外部循环。

function myFunction() {

  var myValue = 0;

  // this will run until "myValue" equals "something"
  while(myValue !== something) {
    if (myValue < 9) {
      // update the value if it is less than 9
    }

    if (myValue === 10) {
      // update the value if it is equal to 10
    }
  }

  return myValue;
}

答案 1 :(得分:0)

尝试将false case放在if语句中。对于true和false,需要单独的while循环。两个循环就足够了。

答案 2 :(得分:0)

你应该避免在html中调用javascript函数,如下所示:

<button onclick="onload()">

Why is using onClick() in HTML a bad practice?