我必须按照视频说明制作测验应用。我按照说明制作应用程序。几乎一切都有效,但在测验结束时我没有得分。 Web控制台在代码的以下部分显示TypeError(粗体字的第16行):
var currentQuestion = 0;
var score = 0;
var totQuestions = questions.length;
var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
function loadQuestion (questionIndex) {
var q = questions[questionIndex];
**questionEl.textContent = (questionIndex + 1) + '. ' + q.question;**
opt1.textContent = q.option1;
opt2.textContent = q.option2;
opt3.textContent = q.option3;
opt4.textContent = q.option4;
};
function loadNextQuestion () {
var selectedOption = document.querySelector('input[type=radio]:checked');
if(!selectedOption){
alert('Please select your answer!');
return;
}
var answer = selectedOption.value;
if(questions[currentQuestion].answer ==answer){
score += 10;
}
selectedOption.checked = false;
currentQuestion++;
if(currentQuestion == totQuestions - 1){
nextButton.textContent = 'Finish';
}
if(currentQuestion == totQuestions){
container.style.display = 'none';
resultCont.style.display = '';
resultCont.textContent = 'Your score: ' + score;
}
loadQuestion(currentQuestion);
}
loadQuestion(currentQuestion);
有人可以指出错误吗? 以下是定义问题的文件:
var questions = [{
"question": "Why do we use the present simple tense?",
"option1": "General truths and facts",
"option2": "Complete action",
"option3": "Continuous action",
"option4": "Continuous action linked with past",
"answer": "1"
}, {
"question": "Why do we use the present continuous tense?",
"option1": "General truths and facts",
"option2": "Complete action",
"option3": "Continuous action",
"option4": "Continuous action linked with past",
"answer": "3"
}, {
"question": "Why do we use the present perfect tense?",
"option1": "General truths and facts",
"option2": "Complete action",
"option3": "Continuous action",
"option4": "Continuous action linked with past",
"answer": "2"
}, {
"question": "Why do we use the present perfect continuous tense?",
"option1": "General truths and facts",
"option2": "Complete action",
"option3": "Continuous action",
"option4": "Continuous action linked with past",
"answer": "4"
}]
答案 0 :(得分:0)
如评论中所述,在JS中,var myvar = some.thing
并不保证您在myvar
中拥有值。
如果some
变量不包含thing
属性,则some.thing
为undefined
,因此myvar
。
简单演示here(使用左下方的控制台按钮)。最后一行会在您的浏览器控制台中引发错误,导致您无法执行undefined.someProperty
。