我創建JavaScript和jQuery的測驗。這幾乎是我想要的地方,但分數計數器似乎並不奏效。我認爲這可能是代碼執行順序的問題。我只是想添加一個到「分數」變量時的「價值」 vaiable(檢查哪個單選按鈕被選中)等於當前問題對象的答案值。更新JavaScript的測驗分數動態
$(document).ready(function() {
var i = -1;
var qNum = 0;
var score = 0;
$(".radbut").hide();
$("br").hide();
//display value upon radio button checked change - for debugging purposes
$('.radbut').change(function() {
var value = ($('input[name="Q"]:checked').val());
alert(value);
});
$("#next").click(function(){
var value = ($('input[name="Q"]:checked').val()); //checks which radio button is checked and sets it to value
i += 1;
qNum += 1;
$(".radbut").show();
$("br").show();
//display questions and variables
$("#questionLoc").text(allQuestions[i].question);
$("#R1").text(allQuestions[i].choices[0]);
$("#R2").text(allQuestions[i].choices[1]);
$("#R3").text(allQuestions[i].choices[2]);
$("#R4").text(allQuestions[i].choices[3]);
$("#qNum").text(qNum);
$("#score").text(score);
$("#value").text(value);
$("#quesVal").text(allQuestions[i].answer);
//add +1 to score if choice matches answer
if (value == allQuestions[i].answer) {
score++;
};
});
});
var allQuestions = [];
function question(question, choices, answer) {
this.question = question;
this.choices = choices;
this.answer = answer;
};
var question1 = new question("Who is Sansa\'s mother?", ["Cercei", "Marjorie", "Catelin", "Lysa"], 3);
var question2 = new question("Where are the Starks from?", ["Winterfell", "King's Landing", "Valyria", "Dorne"], 1);
var question3 = new question("Who is the biggest asshole in this group?", ["Eddard", "Khaleesi", "Bran", "Geoffrey"], 4);
var endSent = new question("End");
allQuestions.push(question1, question2, question3, endSent);
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<title>Game of Thrones Trivia Quiz</title>
</head>
</header>
<h3>"Please choose the correct answer for the question given. Do so promptly - winter is coming.</h3>
<p id="questionLoc">Click "Next" to begin</p>
<input type="radio" name="Q" value= 1 class="radbut" /><span id="R1"></span>
<br />
<input type="radio" name="Q" value= 2 class="radbut" /><span id="R2"></span>
<br />
<input type="radio" name="Q" value= 3 class="radbut" /><span id="R3"></span>
<br />
<input type="radio" name="Q" value= 4 class="radbut" /><span id="R4"></span>
<br />
<br />
<div id="next">Next</div>
<p id="qNum"></p><span>Question</span>
<p id="score"></p><span>score</span>
<p id="value"></p><span>value</span>
<p id="quesVal"></p><span>quesval</span>
</form>
您還可能要繼續到下一個問題,我現在還編輯成我的答案時,取消目前的答案。 – Connum
再次更新以添加一些優化。我想這是僅用於演示樣機,但如果沒有,你應該保存,而不必再收集他們的例如點擊處理函數每次調用(通過jQuery選擇=元素)的jQuery集合到變量。 – Connum