选中每个复选框时触发更改事件

问题描述 投票:1回答:2

我有一个简单的测验,用户可以通过单击下一步来回答多个问题,现在我想在选中复选框时更改复选框背景

这里是演示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");  
      } });

现在,当我运行我的应用程序并单击复选框时,复选框会更改背景,但是当我单击下一步然后单击复选框时,背景不会更改。

要更改此功能我需要更改什么?

javascript jquery html checkbox
2个回答
0
投票
我相信解决方案很简单,只需将像这样的JQuery用作侦听器即可向某些动态添加的元素添加侦听器:

$("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']


0
投票
问题是您正在动态创建元素。但是您的代码仅将事件处理程序附加到现有处理程序上。您需要的是在创建新元素时添加事件处理程序,因此您的代码应如下所示:

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
© www.soinside.com 2019 - 2024. All rights reserved.