无效的输入和重新提交

时间:2016-02-13 06:38:00

标签: javascript dom while-loop

我正在试图弄清楚如何执行以下操作:允许用户输入1到10之间的值,而不允许任何低于或高于该允许范围的值。我要做的是,有效地,告诉用户他们没有得到足够的巧克力,或者他们得到了太多的巧克力,然后再次重新尝试。

我不知道如何在JavaScript中执行此操作。这是我到目前为止的代码:

var numberOfPoundsOrdered;
numberOfPoundsOrdered = prompt("How many lbs of chocolate would you like to order?");
while (numberOfPoundsOrdered < 1 || numberOfPoundsOrdered > 10) {
        numberOfPoundsOrdered = prompt("How many lbs of chocolate would you like to order?");
}

我是JavaScript的新手。如果可能的话,我想在while循环中包含“错误消息”。

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var numberOfPoundsOrdered;
while (true) {
  // Make sure numberOfPoundsOrdered is number before the check.
  numberOfPoundsOrdered = parseInt(prompt("How many lbs of chocolate would you like to order?"), 10);
  
  
  if (numberOfPoundsOrdered < 1) {
    // Do something if number too small.
    console.log("Too less chocolate.");
  } else if (numberOfPoundsOrdered >= 10) {
    // Do something if number too large.
    console.log("Too much chocolate.");
  } else {
    // Cond met, leave
    break;
  }
}
&#13;
&#13;
&#13;

或者同时:

var numberOfPoundsOrdered;
var numValid = false;
do {
  // Make sure numberOfPoundsOrdered is number before the check.
  numberOfPoundsOrdered = parseInt(prompt("How many lbs of chocolate would you like to order?"), 10);

  if (numberOfPoundsOrdered < 1) {
    // Do something if number too small.
    console.log("Too less chocolate.");
  } else if (numberOfPoundsOrdered >= 10) {
    // Do something if number too large.
    console.log("Too much chocolate.");
  } else {
    numValid = true;
  }
} while (!numValid);