我是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>
答案 0 :(得分: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>
答案 1 :(得分: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";
...
}