2011-12-02 69 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的页面,但每次按下按钮,因为一个新的事件附加

显示一个更加警觉
相关问题