【问题标题】:div class is not called on the newly appended checkbox element [duplicate]未在新附加的复选框元素上调用 div 类 [重复]
【发布时间】:2020-02-24 13:39:15
【问题描述】:

我有一个包含类名“复选框按钮”的复选框。当页面加载时,下面的函数可以完美执行。但是当 jquery 成功附加一个新创建的复选框时,下面的函数不会执行。

$(function() {
  $('.button-checkbox').each(function() {
    var $widget = $(this),
      $button = $widget.find('button'),
      $checkbox = $widget.find('input:checkbox'),
      color = $button.data('color'),
      settings = {
        on: {
          icon: 'glyphicon glyphicon-check'
        },
        off: {
          icon: 'glyphicon glyphicon-unchecked'
        }
      };

    // Event Handlers
    $button.on('click', function() {
      $checkbox.prop('checked', !$checkbox.is(':checked'));
      $checkbox.triggerHandler('change');
      updateDisplay();
    });

    $checkbox.on('change', function() {
      updateDisplay();
    });

    function updateDisplay() {
      var isChecked = $checkbox.is(':checked');
      $button.data('state', (isChecked) ? "on" : "off");

      // Set the button's icon
      $button.find('.state-icon').removeClass().addClass('state-icon ' + settings[$button.data('state')].icon);
    }

    function init() {
      updateDisplay();

      // Inject the icon if applicable
      if ($button.find('.state-icon').length == 0) {
        $button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> ');
      }
    }
    init();
  });
});

【问题讨论】:

    标签: javascript php jquery css laravel


    【解决方案1】:

    我可能错了,但它看起来像是事件委托 https://learn.jquery.com/events/event-delegation/ 的问题

    这是你需要的:

    // Attach a delegated event handler
    $( "#list" ).on( "click", "a", function( event ) {
        event.preventDefault();
        console.log( $( this ).text() );
    });
    

    如果您的 HTML 类似于:

    <div class="list-checkboxes">
        <div class="list__item">
          <input type="checkbox" name="checkbox-1" id="checkbox-1">
        </div><!-- /.list__item -->
    
        <div class="list__item">
          <input type="checkbox" name="checkbox-2" id="checkbox-2">
        </div><!-- /.list__item -->
    
        <div class="list__item">
          <input type="checkbox" name="checkbox-3" id="checkbox-3">
        </div><!-- /.list__item -->
      </div><!-- /.list-checkboxes -->
    

    您可以执行以下操作以确保在附加的复选框上触发您的功能:

    $( ".list-checkboxes" ).on( "change", "input[type='checkbox']", function( event ) {
        event.preventDefault();
        console.log( 'this should trigger on the appended checkboxes as well' );
    });
    

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2014-08-25
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2023-04-03
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多