我想調試下面的循環。我從來沒有達到最後的警戒狀態(「YO」)。此外,有趣的是,我期待5警報(typeof ...),但我只得到4.我不能爲我的生活弄清楚爲什麼這是。爲什麼在將alert屬性設置爲javascript變量時,循環會在alert語句之前終止?
function Question(topic,question,choices,correctAnswer){
this.topic = topic;
this.question = question;
this.choices = choices;
this.correctAnswer = correctAnswer;
this.userAnswer = null;
}
var allQuestions;
allQuestions = [
new Question("Addition", "What is 8 + 8?", [16, 18, 64, 28], 16),
new Question("Subtraction", "What is 23-8?", [16, 15, 14, 17], 15),
new Question("Multiplication", "What is 8 * 8?", [16, 18, 64, 36], 64),
new Question("Division", "What is 48/16", [3, "3/2", 4, "8/3"], 3),
new Question("Imaginary Numbers", "What is \u221A(-1)^8?", ["i", "-i", 1, -1], 1)
];
function qToHTML(question) {
var header = "<h2>" + question.topic + "</h2>";
var qText = "<p>" + question.question + "</p>";
var options = "";
for (var i = 0; i < question.choices.length; i++) {
options += "<input type='radio' name='" + question.topic + "' value ='" + question.choices[i] + "'>" + question.choices[i] + "<br>"
}
var wrapper = "<div class='question'></div>";
var HTMLstring;
HTMLstring = header + qText + options;
$("#question-box").append(HTMLstring).wrap(wrapper);
}
$(document).ready(function(){
//render questions
for(var i = 0; i < allQuestions.length; i++){
qToHTML(allQuestions[i]);
}
//collect and check user answers
$('form').on('submit', function() {
var numCorrect = 0;
for(var i = 0; i < allQuestions.length; i++){
// collect answers
var currentQ = allQuestions[i];
currentQ.userAnswer = $("input[name=" + currentQ.topic + "]:checked").val();
alert(typeof currentQ.correctAnswer);
// check answers
if (currentQ.correctAnswer == currentQ.userAnswer) {
numCorrect++;
}
}
window.alert('YO');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Quiz</title>
</head>
<body>
<H1>Dynamic Quiz</H1>
<form>
<div id="question-box"
<!--
<div class="question">
<h2></h2>
<p></p>
<input type="radio" name="" value="">
<input type="radio" name="" value="">
<input type="radio" name="" value="">
<input type="radio" name="" value="">
</div>-->
</div>
<input type="submit" value="submit">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
請發佈完整的代碼示例。 – j08691 2014-10-17 16:04:49
此外,我強烈建議使用'console.log'進行調試,而不是提醒! – berrberr 2014-10-17 16:06:16
字。我還添加了完整代碼 – Goodword 2014-10-17 16:07:23