我使用CodePen创建了一个jQuery测试。代码是有效的,但结果与我想要的不同。我想找一种方法同时显示问题和选项,并用绿色突出显示正确的答案和用红色突出显示错误的答案。以下是我尝试的代码:当用户的回答匹配正确答案时,将div突出显示为绿色,否则为红色。您能让我知道哪里错了吗?
test.js
var quiz = [{
question: "How can you get the type of arguments passed to a function?",
answers: ["using typeof operator", "using getType function", "Both of the above", "None"],
correctAnswer: 0
}, {
question: "Which built-in method returns the character at the specified index?",
answers: ["characterAt()", "getCharAt()", "charAt()", "None"],
correctAnswer: 2
}]
var i = 0;
var score = 0;
$(document).ready(function () {
$('#start').on('click', function () {
$('#questions').text(quiz[i].question);
$('#zero').text(quiz[i].answers[0]);
$('#one').text(quiz[i].answers[1]);
});
});
$(document).ready(function () {
$(document).on('click', '#next', function () {
var answer = $('input[name="answers"]:checked').val();
var answerString = quiz[i].answers[answer];
$('p[class="userAnswer"][value=' + i + ']').text(answerString);
var correctAnswer = quiz[i].correctAnswer;
$('p[class="correctAnswer"][value=' + i + ']').text(quiz[i].answers[correctAnswer]);
if (answer == quiz[i].correctAnswer) {
} else {
$('tr[class="row"][name=' + i + ']').css('background', '#FE2E64');
}
if (i < 2) {
$('.choices').css('display', 'none');
$('#questions').text(quiz[i].question);
$('#zero').text(quiz[i].answers[0]);
$('#one').text(quiz[i].answers[1]);
$('.choices').show('slow');
$('input[name="answers"]').prop('checked', false);
}
});
});