Since
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
Is equivalent to the following code written using .live():
$("table").each(function(){
$("td", this).live("hover", function(){
$(this).toggleClass("hover");
});
});
according to jQuery API.
I bet I’m wrong but isn’t it the same of writing
$("table td").live('hover', function() {});
So, what’s is .delegate() for?
.live()listens ondocumentwhere as.delegate()listens on a more local element, the<table>in that case.They both act the same listening for the events to bubble, the one to
.delegate()just bubbles less before being caught.Your example of:
Isn’t the same, as it again attaches an event handler to
documentand not the<table>, so.delegate()is for more local elements, more efficient in most respects…though it still uses.live()under the covers.Also keep in mind that
$(selector)retrieves the elements, so$("table td")selects a bunch of elements really for no good reason when using.live(), where as$("table").delegate()selects only the<table>elements, so even initially it’s more efficient by not running the selector and discarding the result.