是否多次将事件绑定到jQuery中的元素会产生影响吗?

Jon*_*Jon 11 javascript jquery javascript-events

如果我有下面的代码,如果多次按下新的串行按钮,类serial的文本框将被多次绑定到事件.

即使多次调用bind方法,这会阻碍性能还是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
         }
      });
    }

});
Run Code Online (Sandbox Code Playgroud)

更新:我相信它会将下面的代码添加到MonitorSerialTextBoxes函数修复thiings?

$('.serial').unbind("propertychange keyup input paste");
Run Code Online (Sandbox Code Playgroud)

来自jQuery文档:

如果注册了多个处理程序,它们将始终按照绑定的顺序执行

Rik*_*kus 12

您可以将多个事件处理程序绑定到单个元素.以下将生成一个包含两个onclick事件的按钮:

$("button").bind("click", myhandler);
$("button").bind("click", myhandler);
Run Code Online (Sandbox Code Playgroud)

一种选择是首先取消绑定事件:

$("button").unbind("click").bind("click", myhandler);
$("button").unbind("click").bind("click", myhandler);
Run Code Online (Sandbox Code Playgroud)

这将导致仅一个绑定的单击事件.

如果您正在重新绑定事件,因为您的表单已动态添加元素,那么您可能需要查看live()或新建on(),这可以将事件绑定到可能尚不存在的元素.例:

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

在Webkit开发人员工具(Safari和Chrome)中,您可以通过检查元素来查看绑定到元素的事件,然后在"元素"面板的右窗格中向下滚动.它位于一个名为"Event Listeners"的可折叠盒子下面.Firebug应该具有类似的功能.

  • 如果您使用的是jQuery版本1.7+,则不推荐使用[`.live()`](http://api.jquery.com/live/)方法,而不赞成[`.on()`](http:/ /api.jquery.com/on/)(你提到过),但即使从版本1.4+开始,也建议使用[`.delegate()`](http://api.jquery.com/delegate)比`.live()`. (5认同)