我正在通过如何正确学习JavaScript工作。大约在一半的时间里,您可以创建一个测试应用程序。我可以让它显示第一个问题,然后点击下一步更改到第二个问题。但问题是,当我第三次点击按钮时,屏幕就会清除,而第三个问题就永远不会出现。
我肯定我错过了一些简单的东西。知道我哪里出问题了吗?
app.js:
var allQuestions = [
{question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer:0},
{question: "Who is President of the United States?",
choices: ["George Bush", "Barack Obama", "Hilary Clinton"],
correctAnswer:1},
{question: "What is the best state?",
choices: ["Iowa", "Wisconsin", "Colorado", "North Carolina"],
correctAnswer:1}
];
var score = 0;
var i = 0;
$(document).ready(function() {
$('#next').addClass('hidden');
nextQuestion();
});
function nextQuestion() {
var container = $('#container');
var questionName = allQuestions[i].question
var answer = allQuestions[i].correctAnswer;
var choice = 0;
var question = "<div>" + questionName + "</div>";
container.append(question + "<br>");
var choices = allQuestions[i].choices;
for (var j=0;j<choices.length;j++) {
var choice = choices[j];
var radio = "<input type='radio' data-choice='" + j + "' value='" + choice + "' name='" + allQuestions[i].question + "'>" + choices[j];
container.append(radio + "<br>");
}
$('input:radio').on('click',function() {
choice = $(this).data("choice");
$('#next').removeClass('hidden');
});
$('#next').on('click',function() {
$('#next').addClass('hidden');
if (choice === answer) {
alert("Winner!");
}
if (i < allQuestions.length) {
i += 1;
}
container.empty();
nextQuestion();
});
}Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Survey</title>
<link rel="stylesheet" href="assets/bootstrap.min.css">
<link rel="stylesheet" href="assets/bootstrap.responsive.min.css">
<link rel="stylesheet" href="assets/base.css">
</head>
<body>
<!-- index.html -->
<div id="container">
<script src="js/lib/jquery.min.js"></script>
<script src="js/lib/underscore-min.js"></script>
<script src="js/lib/bootstrap.min.js"></script>
<script src="js/app.js"></script>
</div>
<input type='submit' value='Next' id='next'>
</body>
</html>发布于 2014-05-30 04:11:26
从函数中删除以下代码;您要多次绑定事件。当您单击#next一次时,在响应多个绑定时,它可能会提前多个时间。
$('input:radio').on('click',function() {
choice = $(this).data("choice");
$('#next').removeClass('hidden');
});
$('#next').on('click',function() {
$('#next').addClass('hidden');
if (choice === answer) {
alert("Winner!");
}
if (i < allQuestions.length) {
i += 1;
}
container.empty();
nextQuestion();
});将代码放入DOM就绪事件中,并进行如下修改:
$(function() {
$(document).on('change', 'input:radio', function() {
choice = $(this).data("choice");
$('#next').removeClass('hidden');
});
$('#next').on('click',function() {
$('#next').addClass('hidden');
if (choice === answer) {
alert("Winner!");
}
if (i < allQuestions.length) {
i += 1;
}
container.empty();
nextQuestion();
});
});https://stackoverflow.com/questions/23946769
复制相似问题