Jquery click event propagation
Solution 1
You have to stop event bubbling. In jQuery you can do this by
e.stopPropagation();
in the onclick event of the anchor tag.
$("a").live("click",function(e){alert("clicked!");e.stopPropagation();});
Edit
See this post
jquery Event.stopPropagation() seems not to work
Solution 2
I would use bind
instead of live
for both <tr>
and <a>
and the following code
$("a").bind("click", function(e){ alert("clicked!"); e.stopPropagation() });
for <a>
.
All <a href>
's will work as expected and <tr>
event handler code won't execute after clicking <a>
.
Works in all modern browsers.
ozsenegal
Updated on May 08, 2020Comments
-
ozsenegal about 4 years
I have a table with click events bound to its rows (
<tr>
). There are<a>
elements inside those rows with their own click events assigned.Problem is, when i click on the
<a>
element, it also fires the click event from the parent<tr>
. I don't want this behavior; I just want to fire the<a>
click event.Code:
// Event row TR $("tr:not(:first)").click(function() { $(".window, .backFundo, .close").remove(); var position = $(this).offset().top; position = position < 0 ? 20 : position; $("body").append( $("<div></div>").addClass("backFundo") ); $("body").append( $("<div></div>").addClass("window") .html("<span class=close><img src=Images/close.png id=fechar /></span>") .append( "<span class=titulo>O que deseja fazer?</span>" +"<span class=crud><a href=# id=edit>Editar</a></span>" +"<span class=crud><a href=# id=delete codigo=" + $(this).children("td:first").html() + ">Excluir</a></span>" ) .css({top:"20px"}) .fadeIn("slow") ); $(document).scrollTop(0); }); // <A> Element event $("a").live("click",function() { alert("clicked!"); });
Whenever you click the anchor it fires event from it parent row. Any ideas?
-
ozsenegal over 14 yearsI've a normal table.Then I create new anchor elements promagamatically,and append to that rows.
-
rahul over 14 yearsTry giving return false at the end of the anchor event handler.
-
Nick Craver over 14 yearsAdd a
e.preventDefault();
in there as well for good measure, there's some browser inconsistency between propagation prevention. -
Antony Hatchkins almost 13 years
return false
as well ase.preventDefault()
will prevent the default click action (going to linked page) to happen - which is obviously not what OP wants