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

                  

什么是.live()?

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

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

1
2
3
4
5
6
$(document).ready( function() {
  $('a').click( function() {
    alert("You are now leaving this site");
    return true;
  });
});
注意:.click()相对于.bind()方法仅仅是一个方便的方法,所以下面的方法和上面是等价的: 
1
2
3
4
5
6
$(document).ready(function(){
   $('a').bind('click',function(){
      alert('You are leaving this site');
      return true;
   })
})
但是现在,你通过javascript在页面添加另一个链接。 
1
$('body').append('<div><a href="...">Check it out !</a></div>');
现在,当用户点击链接时,你的方法不会触发。因为当你对页面所有的<a> 节点,绑定事件的时候,那个链接并不存在。所以我们可以简单的使用.live()取代.bind()。 
1
2
3
4
5
6
$(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()也是相同的作用。

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

1
$('a').die();
更特别的,如果我们有其他的事件想保留(像hover或者其他的),我们可以只去掉click事件, 
1
$('a').die('click');
更特别的是,我们可以去掉特定事件的特定方法。 
1
2
3
4
5
6
7
8
9
10
11
12
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()方法相同的目标元素。例如,下面是不行的:

1
2
3
4
5
6
7
8
9
10
$(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找不到任何东西去取消。 

更严重的是:

1
2
3
4
5
6
7
8
9
10
11
12
13
$(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();
原文地址:https://www.cnblogs.com/hannover/p/4107517.html