什麼是.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/