jQuery quiz application how to implement a point based answering system?

时间:2016-04-04 17:00:53

标签: javascript jquery

So I am reasonably new to javascript and jquery. I have been looking at tutorials which have been a good starting point however they all seem to have one question that is right, so they are able to check within a function if the users answer is correct via a if equal to statement for example.

if (answers[i] == userAnswers[i]) { 
        flag = true; 
    } 

What I would like to do however, is have a different value attached to each of the potential answers for example

var 1 = 50
var 2 = 0
var 3 = 10

Question 1

var a = 1
var b = 2
var c = 3
var d = 3

Question 2

var a = 3
var b = 1
var c = 2
var d = 3

What would be the best way to do something like this?

2 个答案:

答案 0 :(得分:1)

First, an assumption:

  • answers[i] contains a number which is what the user picked as an answer to question i (Note: if answers[i] is in fact a character, you can get the integer value by subtracting answers[i] by the ascii value of 'a').

To do what you want to do, simply define a 2-dimensional array score[i][j], where i is the index of the question, and j is the option number (ie the asnwer to question i), then score[i][j] gives the score for this question. So let's say for question 1, the options are as you described above (ie a = good, b = wrong, ...), then you would have

//set the values for the answers
score[1][1] = good; score[1][2] = wrong; score[1][3] =  wrong; score[1][4] = okay
score[2][1] = okay; score[2][2] = good; score[2][3] = wrong;
//more score setting

//get the value of the answer
var score_q1 = score[1][answers[1]]
var score_q2 = score[2][answers[2]]

ie, since answers[i] contains the value of the answer as a number, by calling score[question_nb][answers[question_nb]] you get the score for that question. In this case, there are no if statements. If you want to get the total score, just loop over all questions and sum up the score for that question.

答案 1 :(得分:0)

The best way would be a key/value pair. I would try something like json. You would have your json with a key of good and a value (for points) as 50. The json would look something like below:

var kvPair = {"good":"50", "wrong":"0", "okay":"10"};

then when someone clicks an answer it would run ajax to determine the score:

$.ajax({
    type: "POST",
    dataType: "json",
    url: "someUrl",
    data: kvPair,
    success: function (data) {
        //do something with score data
    },
    error: function (event) {
        ShowErrorLabel("ERROR in ajax call('someUrl'): \n" + "Error : " + event.status + " - " + event.statusText);
    }
});