I have a simple table :
The TR has <tr onclick='alert("row");'>
And the button has :
$("body").on('click',".b",function (e){
alert('button');
e.stopPropagation();
});
However - Although I wrote e.stopPropagation();
it still alerts : "row , button".
Now , I know that the event handler is attached to the body
and the selector is checked against it ( the click start at the button and move up to the body , just like $.live
use to do but against document
...).
But the checking should be for the button
click and not for the TR
click.
It seems that while i'm clicking , it propagates to the "body"
( because I attached event handler to it) and while its way up to the body it activates the click on the TR
.
What is going on here? How can I keep my code ( attach to body) and still have only alert of "button".
I know I can simply do :
$(".b").on('click',function (e){
alert('button');
e.stopPropagation();
});
but I want to know why my current(!) code doesnt work.
The problem is that you're attaching the event handler to the body
, even if it delegates to the .b
element. This event handler is called only after the tr
event handler is called, so it's too late to stop propagation.
As I suppose you want to deal with dynamically added elements and can't simply bind the event handler to the td
, I can suggest you this :
$('body').on('click',"tr",function (e){
alert('row');
});
$("body").on('click',".b",function (e){
alert('button');
e.stopPropagation();
});
Demonstration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With