jQuery事件處理系列-bind與live

  • 62264
  • 0
  • Web
  • 2010-10-21

jQuery的最底層的事件綁定有二個,bind與live,這二個function的差異在bind是針對HtmlElement綁定,而live是對HtmlDocument綁定,使用live時會將selector與事件函式儲存,當任何HtmlElement發生事件都會同時引發HtmlDocument的事件,會檢查引發事件的HtmlElement有沒有符合儲存的selector,符合才會呼叫事件處理函式。

jQuery的最底層的事件綁定有二個,bind與live,這二個function的差異在bind是針對HtmlElement綁定,而live是對HtmlDocument綁定,使用live時會將selector與事件函式儲存,當任何HtmlElement發生事件都會同時引發HtmlDocument的事件,會檢查引發事件的HtmlElement有沒有符合儲存的selector,符合才會呼叫事件處理函式。

 

範例

HTML


<input type='button' value='New Button' class='newButton' />​

按下New Button後,建立新的New Button,此有同樣的功能

 

用bind的寫法


$(function(){  
     //$(".newButton").click(fn) 同等於 $(".newButton").bind("click",fn)
     $(".newButton").bind("click",geterateButton);
});

function geterateButton(){
    $button = $("<input type='button' value='New Button' class='newButton' />");
    //每次新增都還要綁定一次
    $button.bind("click",geterateButton);
    $(this).after($button);    
}

 

用live的寫法


$(function(){
    $(".newButton").live("click",function(){
        //將".newButton"保留
        $(this).after($("<input type='button' value='New Button' class='newButton' />"));    
    });
});​

有看出二者的差異嗎?

bind必需要每一個HtmlElement都要綁定,而live不用,live適合用在動態新增element,如Ajax下載回來的HTML,用live其中相同的selector的HtmlElement,就不用重Bind,可以省去不少麻煩。

 

實際範例,按下Result可實際執行

 

效能問題

因為live是每一個事件發生就會產生比對,有效能上的疑慮,所以我自己寫的一個簡單範例,來測測看,是不是真的比較慢。

bind


$(function(){
    var startTime;
    var $body = $("body");  
    
    for(i=0;i<1000;i++){
        var $newElement = $("<input type='button' value='Button "+  (i+1)  +"' onclick='window.startTime=new Date()' />​");
        $newElement.bind("click",function(){
            alert((new Date() - window.startTime) + "秒後執行");
        });
        
        $body.append($newElement);
    }
});

執行10次平均都在0-1秒之間,與Chrome的Profiler

image

 

live


$(function(){
    var $body = $("body");
    
    for(i=0;i<5000;i++){
        $body.append("<input type='button' value='Button "+  (i+1)  +"' onclick='window.startTime=new Date()'/>​");
    } 
    $("input[type=button]").live("click",function(){
            alert((new Date() - window.startTime) + "秒後執行")            
    });
});

執行10次平均都在0-2秒之間,與Chrome的Profiler

image

看來live真的比較慢,live與bind,最大有1秒左右的差距,要方便或要效能,開發者自己考慮吧。

 

參考資料

.bind()

.live()