Reputation: 4184
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
Upvotes: 0
Views: 1087
Reputation: 9759
Should anybody, like myself, happen to have any tag inside the <a>
, such as <i>
or <span>
, the following condition will match the click not only in the a
area, but also in its children:
$('tr').live('click', function(e) {
var jqTarget = $(e.target);
if (jqTarget.closest("a", jqTarget.closest("tr")[0]).length === 0) {
// event handler
}
}
The explanation is: closest(selector, context)
will return the first parent element (including self) that matches selector
inside the context
element (docs here). Is this returns an element, then the click was made on a anchor or on one of its children.
Upvotes: 1
Reputation: 161
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.
Upvotes: 3
Reputation: 91585
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;
});
});
Upvotes: 0
Reputation: 49
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.
Upvotes: 0
Reputation: 129802
Have your event listener receive a variable 'e', which will be the click event, and check
if($(e.target).is('a'))
return false;
Upvotes: 2