我的JavaScript代码中的html变量在我的问题循环遍历页面后不会显示在屏幕上。我收到此错误消息,TypeError:divOutput为null。在我的所有问题循环完毕之后
这是HTML
<!DOCTYPE html>
<html>
<head>
<title>JavaScript ES2015 Practice</title>
<script type="text/javascript" src="js/output.js"></script>
</head>
<body>
<div id="text">
</div>
</body>
Javascript代码
var quizQuestions;
var quizAnswers;
var correctAnswers;
var wrongAnswers;
var html;
var response;
const questions = [
{
question:"What is the captial of Georgia [type quit to quit]",
answer:"atlanta"
},
{
question:"What is the captial of New York [type quit to quit]",
answer:"albany"
},
{
question:"What is the captial of Texas [type quit to quit]",
answer:"austin"
}
];
const print = (message) =>{
let divOutput = document.getElementById("text");
divOutput.innerHTML = message;
}
for(let i = 0; i < questions.length; i++){
quizQuestions = questions[i].question;
quizAnswers = questions[i].answer;
response = prompt(quizQuestions);
if(response === quizAnswers){
correctAnswers++;
}else{
wrongAnswers++;
}
html = `You got ${correctAnswers} questions right`; //this doesn't display to the screen
} // end of for loop
print(html);
答案 0 :(得分:1)
在onload
回调中移动脚本,以便在
文档中的所有对象都在DOM中,以及所有图像 和子框架已完成加载。
然后你可以获得divOutput
window.onload=function(){
//your script code;
}
脚本应该是:
window.onload = function () {
var quizQuestions;
var quizAnswers;
var correctAnswers = 0;
var wrongAnswers = 0;
var html;
var response;
const questions = [
{
question: "What is the captial of Georgia [type quit to quit]",
answer: "atlanta"
},
{
question: "What is the captial of New York [type quit to quit]",
answer: "albany"
},
{
question: "What is the captial of Texas [type quit to quit]",
answer: "austin"
}
];
const print = (message) => {
let divOutput = document.getElementById("text");
divOutput.innerHTML = message;
}
for (let i = 0; i < questions.length; i++) {
quizQuestions = questions[i].question;
quizAnswers = questions[i].answer;
response = prompt(quizQuestions);
if (response === quizAnswers) {
correctAnswers++;
} else {
wrongAnswers++;
}
html = `You got ${correctAnswers} questions right`; //this doesn't display to the screen
} // end of for loop
print(html);
}
另外,我修改了这个:
var correctAnswers = 0;
var wrongAnswers = 0;
使其更合法地运作