在测验中显示正确和不正确

时间:2016-04-01 19:39:55

标签: javascript jquery

我有一个Javascript测验,它运行正常并显示有多少正确的答案。但是,我还需要它来回答错误的问题。

var score = 0;
var questions = [
    ['Question One?', '1 Answer'],
    ['Question Two?', '2 Answer'],
    ['Question Three?', '3 Answer'],
    ['Question Four?', '4 Answer'],
    ['Question Five?', '5 Answer'],
    ['Question Six?', '6 Answer']
];

var cA = [];

function askQuestion(question) {
    var answer = prompt(question[0], '');
    if (answer == question[1]) {
        alert('Correct!');
        score++;
        cA = question;
    } else {
        alert('Sorry. The correct answer is ' + question[1]);
    }
}

for (var i = 0; i < questions.length; i++) {
    askQuestion(questions[i]);
}

var message = 'You got ' + score;
message += ' out of ' + questions.length;
message += ' questions correct.';
document.write('<p>' + message + '</p>' + cA);

如何显示他们的答案有问题?

1 个答案:

答案 0 :(得分:1)

试试这个;)

&#13;
&#13;
var score = 0;
var questions = [
  ['Question One?', '1 Answer'],
  ['Question Two?', '2 Answer'],
  ['Question Three?', '3 Answer'],
  ['Question Four?', '4 Answer'],
  ['Question Five?', '5 Answer'],
  ['Question Six?', '6 Answer']
];

var cA = [];
var incorrect = [];

function askQuestion(question, index) {
  var answer = prompt(question[0], '');
  if (answer == question[1]) {
    alert('Correct!');
    score++;
    cA = question;
  } else {
    incorrect.push(index);
    alert('Sorry. The correct answer is ' + question[1]);
  }
}

for (var i = 0; i < questions.length; i++) {
  askQuestion(questions[i], i);
}

var message = 'You got ' + score;
message += ' out of ' + questions.length;
message += ' questions correct.<br>' + cA;

message += '<br><br>You answered ' + incorrect.length;
message += ' questions incorrect. These are as follows:';

for(var i in incorrect){
  message += '<p>Q ' + (incorrect[i] + 1) + '. ' + questions[incorrect[i]][0] + '<br>' + questions[incorrect[i]][1] + ' </p>';
}

document.write('<p>' + message + '</p>');
&#13;
&#13;
&#13;