У меня есть сценарий, который отображает вопросы из массива и переключается с одного вопроса на следующий, используя событие .click
на двух кнопках: предыдущем и следующем. Когда я загружаю страницу, селектор $(":radio").change
работает нормально, но когда я нажимаю на предыдущий или следующий, он перестает работать.Почему это событие jQuery .change перестает работать после события .click
Я попытался изменить $("#previous)
на console.log, чтобы узнать, был ли виновником .click
, и он работает. Я предполагаю, что что-то не так с моей функцией отображения, но я не могу понять, почему.
Адрес jsFiddle. А вот проект по GitHub
Вопросы массива
var quizQuestions =
[{
question: "1. Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer:0
},
{
question: "2. Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer:2
},
{
question: "3. Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer:1
}];
JavaScript код (JQuery)
$(document).ready(function(){
var all = quizQuestions,
q = $("#question"),
c = $("#choices"),
ans = [],
current = 0;
display(current);
function display (id) {
var question = all[id].question;
var choices = all[id].choices;
q.html(question);
c.html(function(){
var output = "<form>";
for (var i = 0; i < choices.length; i++) {
output += "<input type='radio' name='question" +id
+ "' value='" + choices[i] + "'> "
+ choices[i] + "<br>";
};
output += "</form>"
// console.log(output);
return output;
});
};
function changeDisplay (dir) {
if (dir == 'next' && current < all.length-1) current++;
if (dir == 'prev' && current > 0) current--;
display(current);
}
function answerQ (q, a) {
ans[q] = a;
console.log(ans);
}
$(":radio").change(function(){
answerQ($(this)[0].name, $(this).val());
});
$("#previous").click(function(){ changeDisplay('prev'); });
$("#next").click(function(){ changeDisplay('next'); });
// console.log("all.length: " + all.length + " | ans: " + ans + " | current: " + current);
});
Существует 'console.log', что я не мог показать на скрипке. Предполагается, что будут отображены «имя» и «значение» выбранного вопроса/ответа. –