jQuery limit what accepts a click() event
Sorry for the bad name, but I have a few approaches in my head and I don't know which if any have potential here. I am trying to make it so that I click on a table cell a Javascript function is called, but only if the child element within that table cell, the 'a' was not clicked on.
Here's some html I have. I can't modify it.
<td class="DayStyle" align="right" style="color:#CEE2ED;border-color:#CEE2ED;border-width:3px; border-style:solid;width:14%;">
<a title="July 19" style="color:#CEE2ED" href="javascript:__doPostBack('myCal','4217')">19</a>
</td>
I'm using this jQuery to accomplish this right now:
$(".myCal").find("td.DayStyle").click(function() {
//DoStuff
});
If, within this function, I get '$(this).attr("class"))', I always get DayStyle, assumingly that's because that's what caught the click.
The behavior that results is that DoStuff happens when the user clicks on either the table cell or the text/"a开发者_Go百科" within the table. The behavior I want is that DoStuff only happens when the table cell is clicked, but not the text within it.
Approaches I'm considering:: 1) Trying to also capture .click() events that click the "a" element and do nothing. 2) Finding where the user is clicking and check if there is text or an "a" at that location. 3) Somehow specifying in the click function that clicking on the "a" or anything with a "title" attribute or something isn't okay.
Try using event.target
$(".myCal").find("td.DayStyle").click(function(e) {
if($(e.target).hasClass('DayStyle')) {
}
});
or
if(!$(e.target).is('a')) {
}
Try this:
$('td.DayStyle a').click(function(event){
try
{
// Prevent click event from travelling up the DOM tree
event.stopPropagation();
}
catch(err)
{
// IE does it this way
window.event.cancelBubble=true;
}
});
You can also use delegate in this case to optimize your code.
$(".myCal").delegate("td.DayStyle", "click", function(e) {
if(!$(e.target).is('a')) {
//do Stuff
}else{ //do nothing or someother logic goes here }
});
精彩评论