2011-12-02 30 views
11

如果我有下面的代碼,如果多次按下新的串行按鈕,類serial的文本框將被綁定到事件多次。多次將事件綁定到jQuery中的元素有一個敲門效應?

即使綁定方法被調用很多次,這是否會妨礙性能或者jQuery是否只註冊一次事件?

$(document).ready(function() { 

    MonitorSerialTextBoxes(); 

    $('#newSerial').click(function() { 

     $.tmpl("productTemplate", mymodel).insertAfter($(".entry").last()); 
     MonitorSerialTextBoxes(); 

    }); 

    function MonitorSerialTextBoxes() { 
     $('.serial').each(function() { 
     // Save current value of element 
     $(this).data('oldVal', $(this).val()); 

     // Look for changes in the value 
     $(this).bind("propertychange keyup input paste", function (event) { 

     // If value has changed... 
     if ($(this).data('oldVal') != $(this).val() && $(this).val().length == 10) { 

      // Updated stored value 
      $(this).data('oldVal', $(this).val()); 

      // Do action 
     } 
     }); 
    } 

}); 

更新:我相信它會做會增加下面的代碼到MonitorSerialTextBoxes功能修復thiings?

$('.serial').unbind("propertychange keyup input paste"); 

從jQuery的文檔:

如果有註冊多個處理程序,他們將永遠在他們被束縛

+1

我不確定沒有測試它的答案,但你可以用Visual Event自己測試它。 http://www.sprymedia.co.uk/article/Visual+Event只需按照頁面上的說明進行操作即可。 –

回答

12

可以綁定多個事件處理程序的順序執行單個元素。下面將產生兩個的onclick事件的按鈕:

$("button").bind("click", myhandler); 
$("button").bind("click", myhandler); 

一個辦法是先解除綁定的事件:

$("button").unbind("click").bind("click", myhandler); 
$("button").unbind("click").bind("click", myhandler); 

這將導致只有一個綁定的click事件。

如果因爲表單動態添加了元素而重新綁定事件,那麼您可能需要查看live()或新的on(),它可以將事件綁定到可能尚不存在的元素。例如:

$("button").live("click", myhandler); // All buttons (now and in 
             // the future) have this handler. 

在Webkit開發工具(Safari和Chrome),你可以看到通過檢查,然後在元素面板的右側窗格中向下滾動被綁定到一個元素是什麼事件。它位於名爲「Event Listeners」的可摺疊框中。 Firebug應該具有類似的功能。

+5

如果你使用的是jQuery版本1.7以上,['.live()'](http://api.jquery.com/live/)方法已被棄用,以支持['.on()'] //api.jquery.com/on/)(你提到過),但是即使從版本1.4+開始,建議使用['.delegate()'](http://api.jquery.com/delegate)而不是'.live()'。 – nnnnnn

2

嗯,我認爲這會導致很多開銷和一些問題,因爲事件綁定不止一次。看看這個簡單的小提琴:http://jsfiddle.net/nicolapeluchetti/syvDu/

<button id='newSerial'>Button</button> 
<div class='serial'>Serial</div> 
<div class='serial'>Serial</div> 
<div class='serial'>Serial</div> 

MonitorSerialTextBoxes(); 

$('#newSerial').click(function() { 
    MonitorSerialTextBoxes(); 

}); 

function MonitorSerialTextBoxes() { 
    $('.serial').each(function() { 


     // Look for changes in the value 
     $(this).bind("click", function(event) { 
      alert("hi"); 
     }); 
    }); 
} 

當加載當你點擊一個div顯示一個alòert的頁面,但每次按下按鈕,因爲一個新的事件附加

顯示一個更加警覺
相關問題