我有一个脚本显示数组中的问题,并使用.click两个按钮上的事件从一个问题切换到下一个问题:上一个和下一个.当我加载页面时,$(":radio").change选择器工作正常,但是当我点击上一个或下一个时它停止工作.
我尝试将其更改$("#previous)为console.log以查看是否.click是罪魁祸首,它似乎正在运行.我认为我的显示功能有问题,但我似乎无法弄清楚原因.
问题数组
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
}];
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
这很可能是因为事件未被委派.加载页面时,您绑定单击事件.但是当操作dom(删除元素)时,事件将被删除.您必须为此使用委托.
像这样:
$('.container').on('change', ':radio', function(){
answerQ( $(this)[0].name, $(this).val() );
});
Run Code Online (Sandbox Code Playgroud)
编辑:我建议你保存或隐藏答案而不是覆盖它们.这样可以更容易地实现以前的功能.