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?
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
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.
来源:https://stackoverflow.com/questions/2244320/jquery-click-event-propagation