.live()
requires you run the selector immediately, unless you're using the result it's very wasteful. The event handler here is attached to document
, so all event of that type from any elements bubbling must be checked. Here's a usage example:
$(".myClass").live("click", function() { alert("Hi"); });
Note that the statement $(".myClass")
ran that selector to find all elements with that class even though we don't care about them, all we wanted was the string ".myClass"
to match later when click
events bubble up to document
.
.delegate()
actually uses .live()
internally, but with a context. The selector is not run immediately, so it's more efficient already, and it doesn't attach to document
(though it can) it's much more local...and all those other events from other element trees you don't care about are never even checked when bubbled...again more efficient. Here's a usage example:
$("#myTable").delegate("td", "click", function() { alert("Hi"); });
Now what happened here? We ran $("#myTable")
to get the element to attach to (admittedly more expensive than document
, but we're using the result. Then we attach an event handler to that (or those in other cases) elements. Only clicks
from within that element are checked against the "td"
selector when they happen, not from everywhere like .live()
does (since everything is inside document
).
bind
,live
anddelegate
. – Kwh