Jquery click event propagation

丶灬走出姿态 提交于 2019-11-27 03:14:45

问题


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?


回答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




回答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.



来源:https://stackoverflow.com/questions/2244320/jquery-click-event-propagation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!