tags:

views:

94

answers:

5

Hi,

I have a table that I want to add a click event to the tr elements. I have managed to do this:

$(function() {
    $('tr').live('click', function() {
        alert($(this).html());
    });
});

However I have anchor tags within some of the td elemets of the row that I don't want the click event to fire for, and just have their default behavior.

Is this possible?

Thanks

+2  A: 

Have your event listener receive a variable 'e', which will be the click event, and check

if($(e.target).is('a'))
   return false;
David Hedlund
+1  A: 

You can try:

 $('tr').not('a').live('click', function() {
qwertypants
That selector gives you "all tr-elements that are not a-elements", which is really just a weird way of selecting "all tr-elements"
David Hedlund
Oops. Thanks for that.
qwertypants
A: 

Yes, this is possible. You need to stop propagation on the anchor elements. This can be done very easily with jquery. See my example below. This code should be in a $(document).ready block.

// Do not propage clicks on deadZone class
$('.deadZone').click( function(e){     
  e.stopPropagation();
});

Then on the anchor tags you would add a class = deadZone.

Zulucap
A: 

You should assign click events to those anchors and set the click function to return false. This prevents the click event from bubbling past the anchor tags.

$(document).ready(function() {
    $('tr a').live('click', function() {
        return false;
    });
});
Soviut
+2  A: 

Try:

$(function() {
    $('tr').live('click', function(event) {
        if($(event.target).is('a')){
            return true;
        }
        alert($(this).html());
    });
});

Here you are returning true if the click was on a link, and this will make the browser perform the default action for the link. If you would return false, then the default behaviour would be prevented, and thus clicking on a link would have no effect.

antti_s
Yeah, I think everyone else is getting this backwards. +1
Alex Sexton
Totally right - I changed the code appropriately. Right answer!
littlechris