我写了这段代码:
$(".awesome").click(function () {
var toStore = $("input[name=name]").val();
if (/^[A-Za-z]+ [A-Za-z]+$/.test(toStore)) {
$("#contain").children().fadeOut(1000);
$("#contain").delay(1000).queue(function () {
$("#contain").append("<h1>Welcome to My Quiz : " + toStore + "</br>" +
"Youll Get 10 Questions To Answer </br> " +
"Here Is the First One:Who is Prime Minister of the United Kingdom? </h1>");
var allQuestions = [
{question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron",
"Gordon Brown",
"Winston Churchill",
"Tony Blair"],
correctAnswer: 0}
];
$("#contain").append("<form><input type='radio' name='ans1' value='David Cameron'>David Cameron</br>" +
" <input type='radio' name='ans1' value='Gordon Brown'>Gordon Brown</br>" +
"<input type='radio' name = 'ans1' value = 'Winston Churchill' > Winston Churchill </br>" +
"<input type='radio' name='ans1' value='Tony Blair'>Tony Blair</br>" +
"<input type='submit' value='Submit' name='submit'></form>");
$("input[name=submit]").click(function () {
var correctAnswer;
if ($("input[name=ans1]").val()) {
var x = "choices";
allQuestions[x] = "David Cameron";
for (var x in allQuestions) {
return correctAmswer = false;
if (allQuestions[x] === "David Cameron") {
return correctAnswer = true;
} else {
return correctAnswer = false;
}
}
}
});
});
} else {
alert("You Must Put a Valid Name");
}
});
});
现在你可以看到我有一个名为“allQuestions”的对象。现在我有 3 个属性:“问题”“选择”和“正确答案”。之后我有一个提交按钮,如果你点击它,它会检查输入 name="ans1" 的值,然后我会遍历对象 "allQuestions" 中的所有选项;如果然后答案是“大卫卡梅隆”,我希望它将正确答案存储为 1 而不是 0;否则我不想存储正确答案,它仍然为 0,因为我之后有更多问题。有什么建议吗?