Jquery Datatables and Bootstrap Toggle Doesn't

2019-03-05 00:20发布

i'm using datatables from : https://www.datatables.net/

and also i'm using Bootstrap Toggle from : http://www.bootstraptoggle.com/

Here is my code :

<table class="table table-striped table-hover" id="table-list-tour">
  <thead>
    <tr><th>Featured</th></tr>
  </thead>
  <tbody>
    <?php foreach ($packages as $package) : ?>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" class="shownCheckbox" id="<?php echo $package->id ?>" data-toggle="toggle">
          </div>
        </td>
      </tr>
    <?php endforeach ?>
  </tbody>
</table>

<Script>
  $('#table-list-tour').DataTable();

  $(".toggle-group").click(function(){
    var selectedCheckBox = $(this);

    var id        = selectedCheckBox.parent().children('input').attr('id');
    var isChecked = selectedCheckBox.is(':checked');

    $.ajax({
      url         : 'A_LINK',
      type        : 'post',
      data        : {'id':id},
      success:function(data)
      {
        console.log(data);
        if (isChecked && data !== '') {
          selectedCheckBox.attr('checked', false);
          alert(data);
        }
      },
      error:function()
      {
        alert('Toggle Failed !');
      }
    });
  });
</script> 

The problem is, in page 1, the AJAX in bootstrap toggle event works perfectly, when i move to page 2, all the ajax did not work at all, why ?

1条回答
smile是对你的礼貌
2楼-- · 2019-03-05 00:36

CAUSE

Pages other than first do not exist in DOM at the time of initialization, that is why your handler never gets called.

SOLUTION

You need to use event delegation by providing selector as a second argument in on() call, see example below:

$(document).ready(function(){
    $('#table-list-tour').DataTable();

    $('#table-list-tour').on('click', '.toggle-group', function(){
        // ... skipped ...
    });   
});

From jQuery on() method documentation:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

See "Direct and delegated events" in jQuery on() method documentation and jQuery DataTables – Why click event handler does not work for more information.

查看更多
登录 后发表回答