我建议存储所有答案,如下所示:
http://jsfiddle.net/Wn8Qg/4/
$(ready);
function ready(){
var allQuestions =
[
{
question: "Whats my real name?",
choices: ["Jhonnatan", "Alberto", "Tatan","Jaime"],
answer: 0
},
{
question: "Who is Colombia's president?",
choices: ["Alvaro Uribe", "Andres Pastrana", "Juan Manuel Santos","Tatan"],
answer: 2
},
{
question: "My favorite super heroe?",
choices: ["Batman", "Flash", "Tatan","Javascript"],
answer: 3
},
{
question: "Wich sports do i practice?",
choices: ["Climbing", "Swimming", "Programming","Running"],
answer: 0
},
{
question: "Whats my dad's name?",
choices: ["Alberto", "Jorge", "Javier","Jose"],
answer: 1
},
{
question: "Whats my favorite color?",
choices: ["Red", "Purple", "Blue","All"],
answer: 2
},
{
question: "My favorite alcoholic drink",
choices: ["Vodka", "Aguardiente", "Rum","Tekila"],
answer: 3
},
{
question: "Whats my favorite kind of music?",
choices: ["Hardcore", "Reggaeton", "Salsa","Programming"],
answer: 0
},
{
question: "How many qestions has this quiz??",
choices: ["20", "8", "10","12"],
answer: 2
},
{
question: "My favorite programming lenguage?",
choices: ["Ruby", "Arduino", "Python","Javascript"],
answer: 3
}
];
var score = 0;
var number = 0;
var question = $('#question');
var choice1 = $('#answer0');
var choice2 = $('#answer1');
var choice3 = $('#answer2');
var choice4 = $('#answer3');
var next = $('#next');
var back = $('#back');
var currentQuestion = $('#current-question');
var answers = new Array(allQuestions.length);
next.click(on_click_next);
back.click(on_click_back);
populate();
function populate() {
currentQuestion.text(number + 1);
question.text(allQuestions[number].question);
choice1.text(allQuestions[number].choices[0]);
choice2.text(allQuestions[number].choices[1]);
choice3.text(allQuestions[number].choices[2]);
choice4.text(allQuestions[number].choices[3]);
$(":radio").prop('checked', false);
if (answers[number] !== null)
$(":radio").eq(answers[number]).prop('checked', true);
}
function on_click_next(){
if($(":radio:checked").length == 1)
{
answers[number] = $(":radio:checked").val();
number++;
if (number < allQuestions.length) {
populate();
} else {
displayResult();
}
}else{
alert('please select an answer before proceed');
}
function displayResult(){
var score = get_score();
currentQuestion.text(allQuestions.length);
$('#question, #alternatives').hide();
$('#next').hide();
$('#score').show();
$('#score').text('Your score is: ' + score + 'pts');
}
}
function get_score()
{
var result = 0;
for(var i = 0; i < answers.length; i++)
if (allQuestions[i].answer == answers[i])
result++;
return result;
}
function on_click_back()
{
if (number == allQuestions.length)
{
$('#question, #alternatives').show();
$('#next').show();
$('#score').hide();
number--;
populate();
}
else
{
if(number > 0)
{
number--;
populate();
}
}
}
}