什么是.live()?javascript
除了让你对Dom元素如今和未来绑定事件以外,.live() 方法和.bind()方法很像。你能够用.live()方法对没有存在的Dom节点绑定事件。考虑下面的状况。java
当用户要离开你的站点时,点击任何链接,你能够警告他:jquery
$(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()怎样工做?app
.live()方法并非绑定到你指定的那个元素上,它其实是绑定到Dom树的根节点(在咱们的例子里,指的是$(document)),把你选定的元素做为参数传递过去。this
因此,当你点击一个元素的时候,点击事件会冒泡到根节点。.live()方法执行时,会检查目标元素是否匹配,事件是不是指定的事件。若是都返回true,才会执行事件。code
任何.live() 均可以被.die()orm
若是你了解.bind(),你确定知道.unbind()。.die()对于.live()也是相同的做用。blog
当去掉上面例子的事件(不想提醒用户),咱们能够简单的:事件
$('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()方法相同的目标元素。例如,下面是不行的:ip
$(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/