简体   繁体   English

在满足第一个 if/else 条件之前,如何停止出现第二个提示? (游戏起始页)

[英]How do I stop the second prompt from appearing until the first if/else condition is satisfied? (Start Page for a game)

If the user name is not entered, the age prompt still comes up, I want the whole prompt to terminate if the user name is not entered, basically, when it says "You cannot proceed without the name" after that the prompt asking for the age still appears, I don't want that to happen.如果没有输入用户名,年龄提示仍然出现,如果没有输入用户名,我希望整个提示终止,基本上,当它说“没有名字你不能继续”之后提示要求年龄仍然出现,我不希望这种情况发生。

Here is my code:这是我的代码:

</style>

<body>
<h1>Welcome to </h1>
<h2> Hangman </h2>
<div class="wrapper">
  <button onclick="myFunction()">Let's start</button>
</div>

<script>
  function myFunction() {
  let person = prompt("Please enter your name", "Marium");
  if (person == null || person == "") {
  alert("You cannot proceed without entering the name");
  } 
  else {
  alert("Hello " + person);
  }
   
   let age= prompt("Please enter your age"); 
  if (age<16) { 
   alert("User below 16 cannot proceed");
   }
    else {
   window.location.href= "sample.html";
   }
}

You just need to insert a return before the alert in the if statement relative to the missing username case:您只需要在 if 语句中的警报之前插入一个与缺少用户名案例相关的return值:

 function myFunction() { let person = prompt("Please enter your name", "Marium"); if (person == null || person == "") { return alert("You cannot proceed without entering the name"); } else { alert("Hello " + person); } let age = prompt("Please enter your age"); if (age < 16) { alert("User below 16 cannot proceed"); } else { window.location.href = "sample.html"; } }
 <h1>Welcome to </h1> <h2> Hangman </h2> <div class="wrapper"> <button onclick="myFunction()">Let's start</button> </div>

Add a return;添加return; after

alert("You cannot proceed without entering the name");

Code:代码:

<body>
<h1>Welcome to </h1>
<h2> Hangman </h2>
<div class="wrapper">
  <button onclick="myFunction()">Let's start</button>
</div>

<script>
  function myFunction() {
  let person = prompt("Please enter your name", "Marium");
  if (person == null || person == "") {
  alert("You cannot proceed without entering the name");
  return;
  } 
  else {
  alert("Hello " + person);
  }
   
   let age= prompt("Please enter your age"); 
  if (age<16) { 
   alert("User below 16 cannot proceed");
   }
    else {
   window.location.href= "sample.html";
   }
}
</style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM