數據我寫了這個代碼:如何存儲與使用JavaScript對象
$(".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個屬性:「問題」,「選擇」和「正確答案」。 然後我有一個提交按鈕,如果你點擊它,它會檢查輸入名稱=「ans1」的值,然後循環對象「allQuestions」中的所有選項; 如果答案是「David Cameron」,我希望它將correctAnswer存儲爲1而不是0; 否則我不想存儲correctAnswer並且它仍然爲0,因爲之後我有更多問題 。 任何建議如何做?
您有一個「return correctAmswer = false;」在你的for ... in循環開始。這是打算嗎? _assigns_值爲'false'以糾正錯誤,然後返回'false'值,但correctAnswer不會保留其值。 – 2013-04-07 05:31:48
不,它沒有打算寫我的correctanmswer,但從這裏的代碼:for(var x in allQuestions){ return correctAmswer = false; if(allQuestions [x] ===「David Cameron」){ return correctAnswer = true;其他{ return correctAnswer = false; }在我看來似乎是一個很好的解決方案。或者我是wrog,即時做得很好? – 2013-04-07 05:51:13