The Difference Between jQuery’s .bind(), .live(), and .delegate()

1. bind()
$('a').bind('click', function() { 
		alert("That tickles!") 
	});

This is the most straight forward binding method. jQuery scans the document for all $('a') elements and binds the alert function to each of their click events.


2. live()

$('a').live('click', function() { 
		alert("That tickles!") 
	});

jQuery binds the alert function to the $(document) element, along with'click' and 'a' as parameters. Any time an event bubbles up to the document node, it checks to see if the event was a click and if the target element of that event matches the 'a' CSS selector. If both are true, the function executes. The live method can also be bound to a specific element (or “context”) other than document, like this:

$('a', $('#container')[0]).live(...);

3. delegate()

$('#container').delegate('a', 'click', function() { 
		alert("That tickles!") 
	});

jQuery scans the document for $('#container'), and binds the alert function along with the click event and 'a' CSS selector as parameters. Any time an event bubbles up to $('#container'), it checks to see if the event was a click and if the target element of that event matches the CSS selector. If both checks are true, it executes the function.

Notice this is similar to .live(), except that it binds the handler to the specified element instead of the document root. The astute JS’er might conclude that $('a').live() == $(document).delegate('a'), right? Well, no, not exactly.

The jQuery team have announced in v1.7 a new method for binding events called on. This method combines the functionality of live, bind, and delegate.

posted @ 2012-04-27 09:36  sam yuan  阅读(114)  评论(0编辑  收藏  举报