Hi hubbs,

1. If you want to throw an alert, you could do it like this:

$(document).ready(function() {
 $('table').click(function(event) {
   var $thisCell, $tgt = $(event.target);
   if ($tgt.is('td')) {
     $thisCell = $tgt;
   } else if ($tgt.parents('td').length) {
     $thisCell = $tgt.parents('td:first');
   }
   // now do something with $thisCell
        if ($thisCell) {
                alert('hello');
        }
 });
});

Definitely take a look at Matt's post, though. It's a more robust solution.

2. The ':first' selector is there in case you have nested tables. It'll select the one closest to event.target.

3. If you don't want anything to occur when clicking on a link's nested spans, then you don't have to check for parents or anything like that. It's much easier. Is it all links in the document? All links in a table? Anyway, you could do something like this:

$('table').click(function(event) {
  if (event.target.nodeName.toLowerCase() === 'a') {
    event.preventDefault();
    // do something
  }
});



--Karl

____________
Karl Swedberg
www.englishrules.com
www.learningjquery.com




On Sep 15, 2008, at 2:06 AM, hubbs wrote:


I was reading a great post on learningjquery.com about event
delegation, and it gave an example of how to account for child/
descendants that might get clicked.

Here is the example show:

$(document).ready(function() {
 $('table').click(function(event) {
   var $thisCell, $tgt = $(event.target);
   if ($tgt.is('td')) {
     $thisCell = $tgt;
   } else if ($tgt.parents('td').length) {
     $thisCell = $tgt.parents('td:first');
   }
   // now do something with $thisCell
 });
});

My question is, how do I do something with $thisCell?  I must be
missing a step here, what is I wanted it to throw an alert?
Also, what is the :first doing in this situation?  Say, I have a link
that has a few nested spans inside, how could I ignore the clicks on
those spans, and only register it as a click on the anchor?

Reply via email to