我正在尝试设计一个页面,向用户询问几个问题,然后在文本框中键入答案。
我正在使用Switch语句生成对不同答案的不同注释。
可以用许多不同的方式键入相同的答案。例如,有可能用户键入“是”或“您下注”而不是键入“是”。
有没有一种方法可以将所有可能的答案都视为一件事情,从而避免出现以下情况:
switch (answers) {
case "Yes":
case "Yep":
case "Yeah":
case "You bet":
case "Sure":
case "Absolutely":
text = "Me too.";
break;
case "No":
case "Nope":
case "Nah":
case "I hate it":
case "I do not":
case "Not at all":
text = "Why not?";
break;
default:
text = "What?"
我想要一个单独的文件,其中包含页面中所有预期答案的所有可能的同义词。
这样,我可能会遇到类似的情况,即使用户键入“ You bet”,“ Yeah”或其他任何内容,它也将显示“是”的注释,而不是“默认”的注释。代名词:
switch (answers) {
case "Yes":
text = "Me too.";
break;
case "No":
text = "Why not?";
break;
default:
text = "What?"
这就是我正在使用的:
function myFunction() {
var text;
var answers = document.getElementById("myInput").value;
switch (answers) {
case "Yes":
case "Yep":
case "Yeah":
case "You bet":
case "Sure":
case "Absolutely":
text = "Me too.";
break;
case "No":
case "Nope":
case "Nah":
case "I hate it":
case "I do not":
case "Not at all":
text = "Why not?";
break;
default:
text = "What?"
}
document.getElementById("comment").innerHTML = text;
}
<p>Do you like waffles?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
最佳答案
这是一种可能的方法:
{
const questions = [
{
text: 'Do you like waffles?',
inputs: {
yes: ['yes', 'yep', 'yeah'],
no: ['no', 'nope', 'nah']
},
replies: {
yes: 'Me too.',
no: 'Why not?',
other: 'What?'
}
},
{
text: 'Do you like pasta?',
inputs: {
yes: ['yes', 'yep', 'yeah'],
no: ['no', 'nope', 'nah']
},
replies: {
yes: 'Me too!',
no: 'Why not?!',
other: 'What?!'
}
},
];
let currentQuestionIndex = -1;
function goToNextQuestion() {
let currentQuestion = questions[++currentQuestionIndex];
document.getElementById('myQuestion').innerHTML = currentQuestion.text;
document.getElementById('myInput').value = '';
document.getElementById('myInput').focus();
}
function answer() {
let currentQuestion = questions[currentQuestionIndex];
const input = document.getElementById('myInput').value;
const replyKey = Object.keys(currentQuestion.inputs)
.find(inputKey => currentQuestion.inputs[inputKey].includes(input))
|| 'other';
document.getElementById('answer').innerHTML = currentQuestion.replies[replyKey];
if (currentQuestionIndex < questions.length - 1) {
goToNextQuestion();
}
}
goToNextQuestion();
}
<p id="myQuestion"></p>
<input id="myInput" type="text">
<button onclick="answer()">Answer</button>
<p id="answer"></p>
注意:这里有附加的包装括号,以防止用常量污染全局范围。不过需要ES6-如果可以使用全局变量,则可以摆脱它们。