我正在尝试做一个小的 Javascript 测验,我试图让它工作的方法是检查单选按钮元素中的值是否与对象属性中的值匹配(标记为正确答案)。
var allQuestions = [{
question: ["Question1?", "Question2?", "Question3"],
choices: [["choice1-1", "choice1-2", "choice1-3", "choice1-4"], ["choice2-1", "choice2-2", "choice2-3", "choice2-4"], ["choice3-1", "choice3-2", "choice3-3", "choice3-4"]],
correctAnswer: ["choice 1-4", "choice2-3", "choice3-2"]}];
var questions = document.getElementById('question');
var button = document.getElementById('next');
var radio = document.getElementsByName('buttons');
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');
var d = document.getElementById('d');
var labels = document.getElementsByName('labels');
for(var j=0; j < radio.length; j++) {
radio[j].value = allQuestions[0].choices[0][j];
}
for (var k=0; k < radio.length; k++) {
labels[k].innerHTML = allQuestions[0].choices[0][k];
}
var score = 0;
questions.innerHTML = allQuestions[0].question[0];
var i = 0;
var correct = allQuestions[0].correctAnswer[i];
button.onclick = function() {
if (i < allQuestions[0].question.length) {
i++;
if(radio.sel)
for(var l=0; l < radio.length; l++) {
questions.innerHTML = allQuestions[0].question[i]; //sets the question at top of page
radio[l].value = allQuestions[0].choices[i][l]; //sets value of each radio button.
//labels[l].innerHTML = allQuestions[0].choices[i][l]; //sets options for each question
a.innerHTML = allQuestions[0].choices[i][0];
b.innerHTML = allQuestions[0].choices[i][1];
c.innerHTML = allQuestions[0].choices[i][2];
d.innerHTML = allQuestions[0].choices[i][3];
}
}
我在想,要将所选单选按钮的值与问题的正确答案相匹配,它应该类似于以下内容:
if(radio.checked.value == allQuestions[0].correctAnswer[i]) {
score++;
}
但是当我把它放在函数的顶部时,这特别不起作用。有什么建议吗?