什么是.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 ; }); }); |
1
2
3
4
5
6
|
$(document).ready( function (){ $( 'a' ).bind( 'click' , function (){ alert( 'You are leaving this site' ); return true ; }) }) |
1
|
$( 'body' ).append( '<div><a href="...">Check it out !</a></div>' ); |
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(); |
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()去掉.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(); |
更严重的是:
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(); |