jQuery是否覆盖事件侦听器

Does jQuery overwrite event listeners?

本文关键字:侦听器 事件 覆盖 是否 jQuery      更新时间:2023-09-26

我有一堆div,每个div都包含一个附带点击事件的删除链接:

  var observeRemoveRoom = function
    $('.remove_room').click(function(){     
      $(this).parent().removeClass('active');
    });
  }

单击它将删除父级(div)的"活动"类。我在窗口加载时调用这个observeRemoveRoom函数,它工作得很好。

问题是,我有另一个函数,它添加了更多相同的div。由于新div中包含的a.remove_room链接不在window.load上,我需要调用observeRemoveRoom

我是否以某种方式复制了事件处理程序?jQuery是否覆盖它们?如果是,我应该解除绑定处理程序吗?

每次调用observeRemoveRoom时,jQuery都会为单击事件添加一个新的唯一事件处理程序函数。

因此,是的,您需要通过不带参数地调用.unbind().unbind()所有当前绑定的处理程序,或者是特定的并传入函数引用。

您可以尝试实时查询以保持它们的更新:http://docs.jquery.com/Plugins/livequery

是的,如果再次调用observeRemoveRoom,您将复制事件处理程序,但这可能不会引起注意,因为您只是在调用removeClass方法,如果找不到类,则该方法将不起任何作用,在触发第一个侦听器后会发生这种情况。

相反,您可以每次取消绑定并重新绑定点击事件,如:

 var observeRemoveRoom = function(){
    var remove_class = function(){     
      $(this).parent().removeClass('active');
    };
    $('.remove_room').off('click', remove_class).on('click', remove_class);
  }

但也就是说,建议您在该函数之外执行此操作,而不是每次绑定和取消绑定事件,例如:

$(document).ready(function(){
    var remove_class = function(){     
      $(this).parent().removeClass('active');
    };
    // If the element exists at dom ready, you can bind the event directly
    $('.remove_room').on("click", remove_class);
    // If the element is added in dynamically, you can [delegate][1] the event
    $('body').on("click", '.remove_room', remove_class);
    // Note: Although I've delegated the event to the body tag in this case
    // I recommend that you use the closest available parent instead
});

http://api.jquery.com/on/#direct-和委托事件:[1]