一半的JavaScript不会在嵌套的if语句中执行

时间:2018-07-12 09:23:45

标签: javascript

我对JavaScript还是很陌生,被要求填写一个嵌套的if问题。我发现执行第二部分有麻烦。当您选择“ B”时,一切都很好,但是当您选择“ G”时,您只需要为第一个语句键入一个变量,然后它就在那里结束。

还可以编写多个嵌套的if语句吗?就像在下面的代码中所说的那样,在我告诉他们“工作很糟糕...”之后,是否可以继续提示用户输入变量?

谢谢!

<!DOCTYPE>
<html>
<head>
    <title>Hello</title>
    <script type="text/javascript">
      var ans;
      var b1;
      var g1;

      ans = prompt ("How are you feeling?\n'B' for Bad | 'G' for Good");

      if (ans == 'B')
      {
        b1 = prompt ("I'm sorry ... 'W'.\nIf not, type 'E'");

        if (b1 == 'W')
        {
          window.alert ("Work sucks ...."); 
        }
        else if (b1 == 'E')
        {
          window.alert ("Here's ..");
        }
      }
      else if (ans == 'G')
      {
        g1 == prompt("That's great! I hope you have a fantastic day ahead!\n'C' to Continue | 'R' to Exit");
        if (g1 == 'C')
        {
          window.alert ("...");
        }
        else if (g1 == 'R')
        {
          window.alert ("Goodbye. Have a lovely day!");
        }
      }
    </script>
</head>
<body>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的代码中有一个错字。要进行分配,它必须为g1 =而不是g1 ==

var ans;
var b1;
var g1;

ans = prompt("How are you feeling?\n'B' for Bad | 'G' for Good");

if (ans == 'B') {
  b1 = prompt("I'm sorry ... 'W'.\nIf not, type 'E'");

  if (b1 == 'W') {
    window.alert("Work sucks ....");
  } else if (b1 == 'E') {
    window.alert("Here's ..");
  }

} else if (ans == 'G') {
  g1 = prompt("That's great! I hope you have a fantastic day ahead!\n'C' to Continue | 'R' to Exit");

  if (g1 == 'C') {
    window.alert("...");

  } else if (g1 == 'R') {
    window.alert("Goodbye. Have a lovely day!");
  }
}