现在的位置: 首页 > 综合 > 正文

jquery中 bind和live区别

2018年01月24日 ⁄ 综合 ⁄ 共 2099字 ⁄ 字号 评论关闭

什么是.live()?

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

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

1 $(document).ready( function()
{
2   $('a').click( function()
{
3     alert("You
are now leaving this site"
);
4     return true;
5   });
6 });

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

1 $(document).ready(function(){
2    $('a').bind('click',function(){
3       alert('You
are leaving this site'
);
4       return true;
5    })
6 })

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

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

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

1 $(document).ready( function()
{
2   $('a').live( 'click'function()
{
3     alert("You
are now leaving this site"
);
4     return true;
5   });
6 });

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

.live()怎样工作?

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

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

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

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

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

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

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

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

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

01 specialAlert
function()
{
02   alert("You
are now leaving this site"
);
03   return true;
04 }
05  
06 $(document).ready( function()
{
07   $('a').live( 'click',
specialAlert );
08   $('a').live( 'click',
someOtherFunction );
09 });
10  
11 //
then somewhere else, we could unbind only the first binding
12 $('a').die( 'click',
specialAlert );

.die()的缺点。

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

01 $(document).ready( function()
{
02   $('a').live( 'click'function()
{
03     alert("You
are now leaving this site"
);
04     return true;
05   });
06 });
07  
08 //
it would be nice if we could then choose specific elements
09 //  
to unbind, but this will do nothing
10 $('a.no-alert').die();

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

更严重的是:

01 $(document).ready( function()
{
02   $('a,form').live( 'click'function()
{
03     alert("You
are going to a different page"
);
04     return true;
05   });
06 });
07  
08 //
NEITHER of these will work
09 $('a').die();
10 $('form').die();
11  
12 //
ONLY this will work
13 $('a,form').die();

抱歉!评论已关闭.