我正在学习JavaScript,并编写了这个相当简单的测验游戏。它询问用户对游戏的答案,然后评估他们的回答。我有一个二维数组用于存储问题和答案。逻辑很清楚。
使用document.write()
方法工作正常。但是,一旦我决定将结果动态地放在HTML中的div
中,那就是爆炸的地方。游戏循环显示问题并记录答案,但屏幕上没有显示。
我确保<script>
位于HTML文件的末尾,位于</body>
之上,以便它仅在加载DOM
后运行。但这没有任何区别。我确定这是一个非常小的问题,但我还是不能指责它。
这是JS代码:
var questions = [
["Which city has the largest population?", "tokyo"],
["What are the small indentations on a golf ball called?", "dimples"],
["What is Tiger Woods's first name?", "eldrick"],
["In which war was Operation Desert Storm conducted?", "gulf war"],
["Which country is bordered by both the Indian and Atlantic Oceans?", "republic of south africa"],
["How many men have walked on the moon?", "12"],
["Which is the most common human blood type?", "O"]
];
var correctQuestions = [];
var incorrectQuestions = [];
var correct = 0;
var incorrect = 0;
//logic for the game
function quiz(questions) {
var numOfQuestions = questions.length;
for (var i = 0; i < numOfQuestions; i++) {
//display question and record answer
var response = prompt(questions[i][0]);
response = response.toLowerCase();
if (response === questions[i][1]) {
correct += 1;
correctQuestions.push(questions[i]);
} else {
incorrect += 1;
incorrectQuestions.push(questions[i]);
}
}
}
//show list of questions
function displayResult(arr) {
for (var i = 0; i < arr.length; i++) {
var show = "<li>" + arr[i][0] + "</li>";
print(show);
}
}
function print(message) {
var outputDiv = document.getElementById("output");
outputDiv.innerHTML = message;
}
quiz(questions);
var output1 = "<h1>Thank You for taking the quiz!</h1>";
output1 += "<h2>You got " + correct + " questions correct:</h2>";
output1 += "<ol>";
print(output1);
displayResult(correctQuestions);
var output2 = "</ol>";
output2 += "<h2>You got " + incorrect + " questions wrong:</h2>";
output2 += "<ol>";
print(output2);
displayResult(incorrectQuestions);
print("</ol>");
完整的代码以及HTML和CSS位于this JSFiddle Link。即使在这里,我选择了onDomready
,只是为了确保它不是“写一个不存在的div”问题,但这也没有任何区别。
答案 0 :(得分:2)
我认为您的print
功能需要更新。
function print(message) {
var outputDiv = document.getElementById("output");
outputDiv.innerHTML += message; // <---- needs to be '+=' to append the message
}