Jquery click event propagation

34,009

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.

Share:
34,009
ozsenegal
Author by

ozsenegal

Updated on May 08, 2020

Comments

  • ozsenegal
    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
    ozsenegal over 14 years
    I've a normal table.Then I create new anchor elements promagamatically,and append to that rows.
  • rahul
    rahul over 14 years
    Try giving return false at the end of the anchor event handler.
  • Nick Craver
    Nick Craver over 14 years
    Add a e.preventDefault(); in there as well for good measure, there's some browser inconsistency between propagation prevention.
  • Antony Hatchkins
    Antony Hatchkins almost 13 years
    return false as well as e.preventDefault() will prevent the default click action (going to linked page) to happen - which is obviously not what OP wants