我正在尝试在 javascript 中进行测验,在其中我使用单选按钮检查提供给用户的答案。它检查第一个条目没问题,但是当它移动到第二个问题时,它会抛出一个未定义的类型错误cannot read property of undefined
。在这条线上,我尝试过使用getElementById
和使用 document.form,但无法弄清楚为什么会出现错误。该代码是第一个问题所用内容的复制和粘贴,效果很好!请帮忙!
var questionsChosen = new Array();
for (var i = 1;i<16 ;i++ )
{
questionsChosen[i]= false;
}
function randomQuestion()
{
var myQuestions = new Array();
myQuestions[1] = "<tr><td><h4>Which one of these authors wrote and illustrated 'Calvin and Hobbes'?</h4></td></tr><tr><td><input type='radio' name='question1' value='Charles Schultz'>Charles Schultz<br><input type='radio' name='question1' id='correct' value='Bill Watterson'>Bill Watterson<br><input type='radio' name='question1' value='Jim Davis'>Jim Davis<br><input type='radio' name='question1' value='Tommy Peters'>Tommy Peters<br><hr/></td></tr>";
myQuestions[2] = "<tr><td><h4>In the Calvin and Hobbes Comic, Who was Calvin's annoying neighbour?</h4></td></tr><tr><td><input type='radio' name='question2' id='correct' value='Susie Derkins'/>Susie Derkins<br><input type='radio' name='question2' value='Samantha Jones'/>Samantha Jones<br><input type='radio' name='question2' value='Sally Parker'/>Sally Parker<br><input type='radio' name='question2' value='Sarah Marsh'/>Sarah Marsh<br><hr/></td></tr>";
for (var k = 1;k<myQuestions.length ;k++ )
{
document.write(myQuestions[k]);
questionsChosen[i]= true;
}
}
function checkAnswers()
{
// use boolean to set whether a question has been asked or not. if it has then check here
// maybe something like if question1==true
if (questionsChosen[1]= true)
{
var correctAnswer = document.myQuiz.question1[1].value;
var userAnswer;
for (i=0; i<document.myQuiz.question1.length; i++)
{
if (document.myQuiz.question1[i].checked==true)
{
userAnswer =document.myQuiz.question1[i].value
}
}
document.write("<br><br>Which one of these authors wrote and illustrated 'Calvin and Hobbes'?");
document.write("<br>Your chosen answer is: "+userAnswer);
if (correctAnswer == userAnswer)
{
document.write("<br>Correct!");
}
else document.write("<br>Incorrect... The answer was "+ correctAnswer);
}
if (questionsChosen[2]= true)
{
var correctAnswer = document.myQuiz.question2.value;
var userAnswer;
for (i=0; i<document.myQuiz.question2.length; i++)
{
if (document.myQuiz.question2[i].checked==true)
{
userAnswer =document.myQuiz.question2[i].value
}
}
document.write("<br><br>In the Calvin and Hobbes Comic, Who was Calvin's annoying neighbour?");
document.write("<br>Your chosen answer is: "+userAnswer);
if (correctAnswer == userAnswer)
{
document.write("<br>Correct!");
}
else document.write("<br>Incorrect... The answer was "+ correctAnswer);
}
}
`