我正在尝试进行一个小的Javascript测验,而我试图让它工作的方式是检查并查看单选按钮元素中的值是否与对象属性中的值匹配(标记为correctAnswer)。
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++;
}
但是当我把它放在函数的顶部时,这个特别不起作用。有什么建议吗?
答案 0 :(得分:0)
radio.checked返回一个布尔告诉你,无论是否检查了该无线电,你都不能用值链接它。
正确的方法是循环使用相同名称的所有无线电并获取已选中的无线电的值:
value = '';
for( i in radio ) {
if ( radio[i].checked )
value = radio[i].value;
}
您必须根据需要进行修改