【问题标题】:Fire on change event in each checkbox when its checked选中时触发每个复选框中的更改事件
【发布时间】:2019-12-13 11:02:15
【问题描述】:

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

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

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

我需要更改什么才能使其正常工作??

【问题讨论】:

  • $("input[type='checkbox']").once(...$("input[type='checkbox']").one(...
  • @Eldar 那是什么意思?我希望在每次单击时都应更改背景的复选框
  • @Eldar 如果它在我提供的 jsfiddle 上运行,你能告诉我们你的解决方案吗?
  • 似乎这个标题误导了我。你想要的只是触发一次事件处理程序?
  • @Eldar 我希望在每次单击复选框时触发 on change 事件

标签: javascript jquery html checkbox


【解决方案1】:

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

 function displayNext() {
    quiz.fadeOut(function() {
      $('#question').remove();

      if (questionCounter < questions.length) {
        var nextQuestion = createQuestionElement(questionCounter);
        // here we add event handler for newly created checkboxes.
        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

【讨论】:

    【解决方案2】:

    我相信解决方案很简单,将侦听器添加到一些动态添加的元素中,您只需像这样使用 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'],即(或将成为)它的子级。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 2010-10-30
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多