具有多个默认值的Javascript Switch语句
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了具有多个默认值的Javascript Switch语句相关的知识,希望对你有一定的参考价值。
我是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>
答案
您需要有一个数组来显示消息数量,用户在发送答案时需要获取。
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>
另一答案
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";
...
}
以上是关于具有多个默认值的Javascript Switch语句的主要内容,如果未能解决你的问题,请参考以下文章
Javascript将具有多个值的选定选项从一个列表移动到另一个列表
使用 JavaScript,如何在具有多个值的日期列的表中突出显示“今天”的每个日期
JavaScript对于switch语句中的case后键入值的带不带引号