我正在进行一项测验,显示您正确的问题。我设法让它与第一个问题一起工作,但我正在努力弄清楚如何遍历我的数组中的所有其他问题。
这是我的JS代码:
var questionArray = new Array (8);
questionArray [0] = "q1"
questionArray [1] = "q2"
questionArray [2] = "q3"
questionArray [3] = "q4"
questionArray [4] = "q5"
questionArray [5] = "q6"
questionArray [6] = "q7"
questionArray [7] = "q8"
var correctAnswers = 0;
function checkQuestions()
{
var questions = document.getElementsByName(questionArray[0]);
var numberOfRadios = questions.length;
for( var i = 0; i < numberOfRadios; i++)
{
if(questions[i].checked)
{
if(questions[i].value == "correct")
{
correctAnswers++
}
}
}
document.getElementById("correctAnswers").innerHTML = "You got:" + "<br>" + correctAnswers + "/8!!";
}
答案 0 :(得分:0)
questionArray[0]
返回&#34; q1&#34;。
如果您只有该名称的一个元素,则questions.length
将等于1。
因此,您的for
循环只会迭代一次。
你想做什么,是这样的:
function checkQuestions()
{
for( var i = 0; i < questionArray.length; i++)
{
//I assume you have only one question per name, if not then you need id
var question = document.getElementsByName(questionArray[i])[0];
if(question.checked)
{
if(question.value == "correct")
{
correctAnswers++;
}
}
}
document.getElementById("correctAnswers").innerHTML = "You got:" + "<br>" + correctAnswers + "/8!!";
}
答案 1 :(得分:0)
循环问题..
function checkQuestions()
{
for (var j = 0; j < questionArray.length; j++)
var questions = document.getElementsByName(questionArray[j]);
...
}
document.getElementById("correctAnswers").innerHTML = "You got:" + "<br>" + correctAnswers + "/8!!";
}