我正在尝试创建JavaScript测验。 该功能将检查用户的输入值。 如果是对的;它会改变这个问题。
确切代码请参阅JSFiddle
可能有更多有效和传统的方法来实现我想要做的事情。当前的问题是该函数每次运行时都会从顶部运行(显然)
function checkAnswer() {
var question = document.getElementById("ques").innerHTML;
var userAnswer = document.getElementById("answer").value;
if (userAnswer === "New York City") {
alert("correct!");
question = "What is the best college football team?";
if (userAnswer === "Alabama") {
alert("Correct!");
question = "Next question will go here and so on..."
}
}
}
答案 0 :(得分:1)
如果您有许多问题需要验证,我会采取以下方法。它可以为您提供任意数量的问题而无需重复代码。
首先,将您的问题存储在一个数组中:
var arr = ["one two three", "4 5 6"];
将计数器设置为零,并将总计(以衡量用户绩效):
var count = 0;
var total = 0;
缓存元素:
var questionEl = document.getElementById('question');
var userAnswerEl = document.getElementById("answer");
将将问题写入新函数的代码分开。它根据柜台写出问题:
function writeQuestion() {
if (count < arr.length) {
questionEl.innerHTML = "Write " + arr[count];
} else {
alert('No more questions. You have scored ' + total);
}
}
function check() {
userAnswer = userAnswerEl.value.toLowerCase();
if (userAnswer === arr[count]) {
alert('correct');
count++;
total++;
writeQuestion();
} else {
alert('Sorry Wrong!');
count++;
writeQuestion();
}
}
答案 1 :(得分:1)
我绝不建议以这种方式做事,但这里是如何让你的jsfiddle工作:
function check() {
var question = document.getElementById('question').innerHTML
var userAnswer = document.getElementById("answer").value;
//Makes answer lowercase
userAnswer = userAnswer.toLowerCase();
//question one
if (question === "Write One, Two, Three..") {
if (userAnswer === "one two three") {
alert('correct');
}
else {
alert('Sorry Wrong!');
}
//question two
document.getElementById('question').innerHTML = "Write 4, 5, 6";
}
else {
if (userAnswer === "4 5 6") {
alert("correct!");
}
else {
alert('Sorry Wrong!');
}
}
}
一种简单的方法就是将你的问题放在一个数组中:
var QandA = [
["question1...", "answer1...."],
["question2...", "answer2...."],
["question3...", "answer3...."],
["question4...", "answer4...."]
];
function check()
{
// No more questions?
if (0 === QandA.length) return;
// Check answer
var userAnswer = document.getElementById("answer").value.toLowerCase();
if (userAnswer === QandA[0][1]) {
alert("Correct");
}
else {
alert("Incorrect");
}
// Delete that question
QandA.shift();
// And move to next
if (0 != QandA.length) {
document.getElementById('question').innerHTML = QandA[0][0];
}
}
答案 2 :(得分:0)
if (userAnswer === "New York City") {
alert("correct!");
question = "What is the best college football team?";
if (userAnswer === "Alabama") {
alert("Correct!");
question = "Next question will go here and so on..."
}
}
此块仅在userAnswer
为"New York City"
时运行,但在其中,您测试userAnswer
是否为"Alabama"
- 这将永远不会成立。您可能希望将第二个if
移到第一个if
块之外。
您似乎正在分配question
但未使用该值。如果您认为通过为question
分配一个不起作用的值来更新问题文本。我想你正试图这样做:
question = document.getElementById("ques");
// later on...
question.innerHTML = "this is another question";
// even later...
question.innerHTML = "and here is a new question";
那会为你更新页面,因为question
会指向一个DOM节点,你可以在那里设置.innerHTML
,但是你编写它的方式,你设置{{1最初是一个字符串值,然后是其他字符串值,但不管怎么说都不使用它们。