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.

转载于:https://www.cnblogs.com/cnforest/archive/2012/04/27/2473006.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值