views:

123

answers:

1

I have a table which may contain other inner tables (it's not possible to edit generated markup). I want to create a delegate function for row mouseenter and mouseleave which only triggers for the associated main table rows (and not inner tables rows), as following:

  $("#tableid").delegate("tr", "mouseenter mouseleave", function(e) {
    //do stuff here
  });

But with this selector it also selects the inner table rows, so how can I modify the selector to avoid selecting inner table rows?

+2  A: 

You can use .delegate() with a slightly different selector, like this:

$("#tableid").delegate("#tableid > tbody> tr", "mouseenter mouseleave", function(e) {
  //do stuff, for example $(this).toggleClass("hover");
});​

This works since you want <tr> elements that are direct child rows, but there's a <tbody> in-between you need to account for. You can test a working demo here.

Nick Craver
hmm, did not realize that, +1 for *the* answer.
Sarfraz
Do you consider it a bug that `"> tbody > tr"` is not supported? That the table id must be duplicated in the delegate selector?
Crescent Fresh
@Crescent - I don't consider it a bug, anything with a context that must be independently checked upon each event occurrence cannot be *overall* relative, at least I don't see how. You need an absolute or independently relative selector, for example `"tbody > tr"` works (but not for this question), but *starting* with a relative selector would make it relative to...? Remember with `.delegate()` you're attaching a handler to an element, just (*possibly*) using a selector to do so, but it's thrown away after that, unlike live which continues to use it, but it can't be relative to a *context*.
Nick Craver