我有一个简单的测验,用户可以通过单击下一步来回答多个问题,现在我想在选中复选框时更改复选框背景
这里是演示quiz demo
这是我尝试过的
选中复选框时更改背景颜色的功能
$("input[type='checkbox']").on('change', function(){
console.log('clicked');
if($(this).is(":checked")){
console.log('Chodzi')
$(this).addClass("input-before");
}
else{
console.log('Nie chodzi');
$(this).removeClass("input-before");
} });
现在,当我运行我的应用程序并单击复选框时,复选框会更改背景,但是当我单击下一步然后单击复选框时,背景不会更改。
要更改此功能我需要更改什么?
$("section").on('change',"input[type='checkbox']", function(){
console.log('clicked');
if($(this).is(":checked")){
console.log('Chodzi')
$(this).addClass("input-before");
}
else {
console.log('Nie chodzi');
$(this).removeClass("input-before");
}
});
这是您的fiddle已通过我的编辑进行了更新因此,基本上,您必须将侦听器添加到容器中,它会将侦听器“传播”到每个(或将成为其子级的
input[type='checkbox']
。
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if (questionCounter < questions.length) {
var nextQuestion = createQuestionElement(questionCounter);
nextQuestion.find("input[type='checkbox']").on('change', function() {
console.log('clicked');
if ($(this).is(":checked")) {
console.log('Chodzi')
$(this).addClass("input-before");
} else {
console.log('Nie chodzi');
$(this).removeClass("input-before");
}
});
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value=' + selections[questionCounter] + ']').prop('checked', true);
}
// Controls display of 'prev' button
if (questionCounter === 1) {
$('#prev').show();
} else if (questionCounter === 0) {
$('#prev').hide();
$('#next').show();
}
} else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
}
});
}
工作中fiddle