简体   繁体   中英

Stop Propagation not working

I'm trying to stop the bubbling of event of an inner checkbox to the click event of the tr element.

I have the following mark up:

<table border="1">
  <tr class="row">
    <td>
      Item 1
    </td>
    <td>
      <input type="checkbox" class="cb">
    </td>
  </tr>
  <tr class="row">
    <td>
      Item 2
    </td>
    <td>
      <input type="checkbox" class="cb">
    </td>
  </tr>
</table>

The rows are dynamically added, so to add listeners automatically to dynamically added elements, I used the following code:

$(document).ready(function() {
  $('body').off('click.row').on('click.row', '.row', function() {
    alert(1);
  });
  $('body').off('change.cb').on('change.cb', '.cb', function(e) {
    e.stopPropagation();
    alert(2);
  });
});

However the event still bubble up to the tr element. I tried also the following:

e.stopImmediatePropagation();
window.event.cancelBubbles = true;
e.bubbles = false;

none seemed to work.

I reproduced this issue with JSFiddle:

JSFiddle

In this case, there is no event bubbling occuring because you have different events defined on different elements that just so happen to both fire when a mouse clicks on the check box (because you have also clicked a row).

You should either not add the row click event listener at all, or move stopPropagation to the the other handler to stop it from firing.

$(document).ready(function() {
  $('body').off('click.row').on('click.row', '.row', function() {
    e.stopPropagation();
    alert(1);
  });
  $('body').off('change.cb').on('change.cb', '.cb', function(e) {       
    alert(2);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM