[jQuery] Finding row index of clicked table element; testing if element is parent of another element; is there a better way?
My main requirement is:
I want to put a click handler on a <div> containing a table that
allows me to determine which row of the table has been clicked, using
event delegation as the table may be updated dynamically, and could be
quite large.
With a secondary requirement arising:
I want to determine if a particular DOM element or jQuery object is an
ancestor of another. The solutions I found on the web all assume that
the putative parent is specified using a selector string, which
doesn't help me as I may have many elements that are not easily
distinguished by selector.
...
I have constructed some code that does what I want, but it doesn't
feel very "jQuery-like" - it seems to be unreasonably clumsy, and I
can't help feeling there is an easier way.
Am I missing something, and can someone point me at it?
{{{
/**
* Helper function returns a click event handler for row selection:
* determines which row has been selected, then pops up a local
context menu
* to allow that row to be associated with a data selection option.
*/
shuffl.card.dataworksheet.rowSelect = function (card, cbody)
{
function select(event)
{
cbody.find("tbody tr").each(function (rownum) {
// this = row element in dom
// Is the current row element an ancestor of the event
target?
if (jQuery(this).find("*").index(event.target) >= 0) {
alert("Selected row number "+rownum);
};
});
return this;
};
return select;
};
}}}
The handler is bound using a call like this:
{{{
cbody.click(shuffl.card.dataworksheet.rowSelect(card, cbody));
}}}
#g