2015-10-21 34 views
-1

我正在学习JavaScript,并撰写了这个相当简单的问答游戏。它询问用户游戏的答案,然后评估他们的回答。我有一个二维数组用于存储问题以及答案。逻辑清楚。显示JavaScript输出到document.getElementById屏幕的错误

事情与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

只是好奇。什么导致了downvote? –

回答

2

它在我看来像你的print功能需要更新。

function print(message) { 
    var outputDiv = document.getElementById("output"); 
    outputDiv.innerHTML += message; // <---- needs to be '+=' to append the message 

} 
+0

OP还通过标记将LI元素附加到DIV,这是无效的,并且会触发浏览器错误更正(可能会做任何事情)。 – RobG

+0

在JSFiddle中工作正常 - https://jsfiddle.net/8c4qq11z/1/。我还更新了代码,使其更清晰一些。 –

+0

@RobG - 这会更好的JS? https://jsfiddle.net/8c4qq11z/3/ –