我正在嘗試在JavaScript中進行測驗,其中我使用單選按鈕檢查提供給用戶的答案。它會檢查第一個條目,但是當它移動到第二個問題時,會拋出一個未定義的類型錯誤cannot read property of undefined
。在這條線上,我試圖用getElementById
和使用document.form搞亂,但一直未能找出錯誤原因。該代碼是複製和粘貼什麼用於第一個問題,它工作正常!請幫忙!帶有單選按鈕的JavaScript表單
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);
}
}
`
這種情況發生在頁面解析後調用document.write()時。它會自動調用'document.open()',它清除所有以前的JS和HTML。 – Teemu
那麼有沒有辦法讓我解決這個問題?我是否堅持寫文件直到所有的答案都產生了? – springdo
只是再次通過它並更改document.write()stmnts寫入所有更大的字符串。然後一次打印出來!謝謝您的幫助! – springdo