javascript - 验证来自 prompt() 的响应。再次提示无效响应

标签 javascript prompt

我想这样做,如果用户不输入“1”或“2”,则必须重新回答问题。我尝试了 prompt{choice1}; 但它不起作用。

有什么解决办法吗?

var choice1 = prompt("You see a bear on your campsite, What do you do ? Type 1 if you start running into the woods or type 2 if you fight the bear.");

if (choice1 == "1") {

  for (var i = 2; i < 3; i++) {
    alert("You start running into the woods. You stop, Out of breathe and realize you somehow got cut in your left arm.");
  }

} else if (choice1 == "2") {

  for (var b = 0; b < 1; b++) {
    alert("You look around you to find something that could help you fight off the bear. You see a rock and you pick it up. The bear is getting ready to attack and right away you throw the rock");
  }

} else {}

最佳答案

Working fiddle

使用 do..while 循环:

do {
  var choice1 = prompt("You see a bear on your campsite, What do you do ? Type 1 if you start running into the woods or type 2 if you fight the bear.");

  if (choice1 == "1") {

    for (var i = 2; i < 3; i++) {
      alert("You start running into the woods. You stop, Out of breathe and realize you somehow got cut in your left arm.");
    }

  } else if (choice1 == "2") {

    for (var b = 0; b < 1; b++) {
      alert("You look around you to find something that could help you fight off the bear. You see a rock and you pick it up. The bear is getting ready to attack and right away you throw the rock");
    }

  }
}
while (choice1 != "1" && choice1 != "2");

希望这对您有所帮助。

关于javascript - 验证来自 prompt() 的响应。再次提示无效响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39670609/

相关文章:

javascript - 动态创建图像上的滑动面板

javascript - 类型错误 : Cannot read property 'src' of undefined when loading script in React Enzyme

javascript - 将 'prompt()' 的结果拆分为数组中的项目?

javascript - 提示时取消和空输入的不同值

Python + bash 提示符 : how to print width calculation wrappers?

javascript - 使 JavaScript 提示文本只读

javascript - Google plus share 设置自定义标题、描述、图像并且不使用 og meta

javascript - 如何在firefox上使用parent.parent.document.getElementById? ASP.NET

javascript - jquery 选择 div 内的测试输入

linux - bash PS1 : line wrap issue with non-printing characters from an external command