具有多个默认值的Javascript Switch语句

问题描述 投票:0回答:2

我是JavaScript的初学者。如果我不能清楚地解释我需要什么,我很抱歉。

我正在尝试设计一个包含一些问题的页面。答案必须在文本框中输入。

我使用Switch语句为所有可接受的答案生成不同的评论。

至于不被接受的答案,我想要的不仅仅是默认消息。

例如,如果用户第一次键入未接受的答案,则会显示一条消息,例如“这不是可接受的答案”。在用户的第二个未接受的答案上会显示一条不同的消息,例如“请再试一次”......等等大约五次,然后它将循环回到第一个默认消息。

我只是不知道如何实现这一点......这就是我到目前为止所做的:

function myFunction() {
  var text;
  var colors = document.getElementById("myInput").value;
  switch (colors) {
    case "White":
      text = "White is a nice color.";
      break;
    case "Blue":
      text = "I also like blue. It reminds me of the ocean.";
      break;
    case "Red":
      text = "Red is also nice.";
      break;
    default:
      text = "That is not an acceptable answer";
  }
  document.getElementById("comment").innerHTML = text;
}
<p>What is your favorite color from the USA flag?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
javascript switch-statement
2个回答
0
投票

您需要有一个数组来显示消息数量,用户在发送答案时需要获取。

var count = 0;
var messages = ["That is not an acceptable answer.", "Please try again!", "Still wrong.", "I don't understand.", "Consider visiting the 'help page' before moving on."];

根据该计数,在default案例中显示消息。

default:
  text = messages[count%messages.length];
  count++;

完整的工作片段

var count = 0;
var messages = ["That is not an acceptable answer.", "Please try again!", "Still wrong.", "I don't understand.", "Consider visiting the 'help page' before moving on."];

function myFunction() {
  var text;
  var colors = document.getElementById("myInput").value;
  switch (colors) {
    case "White":
      text = "White is a nice color.";
      break;
    case "Blue":
      text = "I also like blue. It reminds me of the ocean.";
      break;
    case "Red":
      text = "Red is also nice.";
      break;
    default:
      text = messages[count%messages.length];
      count++;
  }
  document.getElementById("comment").innerHTML = text;
}
<p>What is your favorite color from the USA flag?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>

0
投票
    var counter = 0;
    function myFunction() {
        var text;
        var colors = document.getElementById("myInput").value;

        switch(colors) {
            case "White":
                text = "White is a nice color.";
            break;
            case "Blue":
            text = "I also like blue. It reminds me of the ocean.";
            break;
            case "Red":
            text = "Red is also nice.";
            break;
            default:
            text = getText(counter++);
        }
        counter = counter > 5 ? 0 : counter;
        document.getElementById("comment").innerHTML = text;
    }

function getText(counter) {
    switch(counter):
       case 1:
          return "some text";
       case 2:
          return "some text";
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.