0

我正在尝试做一个小的 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++;
}

但是当我把它放在函数的顶部时,这特别不起作用。有什么建议吗?

4

1 回答 1

0

radio.checked 返回一个布尔值,告诉您,无论该收音机是否已检查,您都不能将其与值链接起来。

正确的方法是遍历所有具有相同名称的无线电并获取选中的无线电的值:

value = '';
for( i in radio ) {
    if ( radio[i].checked )
        value = radio[i].value;
}

您必须根据自己的需要进行修改

于 2013-03-20T20:07:05.383 回答