jquery .live() .delegate() .bind() .click()区别

什么是.live()?

除了让你对Dom元素现在和将来绑定事件之外,.live() 方法和.bind()方法很像。你可以用.live()方法对没有存在的Dom节点绑定事件。考虑下面的情况。

当用户要离开你的站点时,点击任何连接,你可以警告他:

$(document).ready( function() {
  $('a').click( function() {
    alert("You are now leaving this site");
    return true;
  });
});

注意:.click()相对于.bind()方法仅仅是一个方便的方法,所以下面的方法和上面是等价的:

$(document).ready(function(){
   $('a').bind('click',function(){
      alert('You are leaving this site');
      return true;
   })
})

但是现在,你通过javascript在页面添加另一个链接。

$('body').append('<div><a href="...">Check it out !</a></div>');

现在,当用户点击链接时,你的方法不会触发。因为当你对页面所有的<a> 节点,绑定事件的时候,那个链接并不存在。所以我们可以简单的使用.live()取代.bind()。

$(document).ready( function() {
  $('a').live( 'click', function() {
    alert("You are now leaving this site");
    return true;
  });
});

现在,如果你添加一个链接到页面,这个绑定的方法就会工作。

.live()怎样工作?

.live()方法并不是绑定到你指定的那个元素上,它实际上是绑定到Dom树的根节点(在我们的例子里,指的是$(document)),把你选定的元素作为参数传递过去。

所以,当你点击一个元素的时候,点击事件会冒泡到根节点。.live()方法执行时,会检查目标元素是否匹配,事件是否是指定的事件。如果都返回true,才会执行事件。

任何.live() 都可以被.die()

如果你了解.bind(),你肯定知道.unbind()。.die()对于.live()也是相同的作用。

当去掉上面例子的事件(不想提醒用户),我们可以简单的:

$('a').die();

更特别的,如果我们有其他的事件想保留(像hover或者其他的),我们可以只去掉click事件,

$('a').die('click');

更特别的是,我们可以去掉特定事件的特定方法。

specialAlert = function() {
  alert("You are now leaving this site");
  return true;
}

$(document).ready( function() {
  $('a').live( 'click', specialAlert );
  $('a').live( 'click', someOtherFunction );
});

// then somewhere else, we could unbind only the first binding
$('a').die( 'click', specialAlert );

.die()的缺点。

当使用.die()去掉.live()时,你只能用和.live()方法相同的目标元素。例如,下面是不行的:

$(document).ready( function() {
  $('a').live( 'click', function() {
    alert("You are now leaving this site");
    return true;
  });
});

// it would be nice if we could then choose specific elements
//   to unbind, but this will do nothing
$('a.no-alert').die();

.die()是绑定到由.live()创建的根节点,然后匹配目标元素,去掉他们。但是在上面的例子中,.live()绑定的是$('a.no-alert'),所以jQuery找不到任何东西去取消。

更严重的是:

$(document).ready( function() {
  $('a,form').live( 'click', function() {
    alert("You are going to a different page");
    return true;
  });
});

// NEITHER of these will work
$('a').die();
$('form').die();

// ONLY this will work
$('a,form').die();

参考文章:http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

转载于:https://my.oschina.net/networker/blog/53406

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值