使用单个新事件覆盖绑定到元素的所有JavaScript事件

jer*_*ome 24 javascript jquery events event-handling event-binding

假设整个站点中存在大量元素,这些元素具有未知数量和绑定到它们的事件类型.

如果我需要使用一个绑定事件覆盖所有这些事件,并且只触发该事件,那么有哪些建议?

我将事件绑定到click事件处理程序,我正在使用jQuery.

提前致谢.

Mat*_*ens 50

你在找jQuery#unbind.

要删除元素或一组元素上的所有事件处理程序,只需执行以下操作:

$('.some-selector').unbind();
Run Code Online (Sandbox Code Playgroud)

要仅取消绑定点击处理程序,请使用unbind('click'):

$('.some-selector').unbind('click');
Run Code Online (Sandbox Code Playgroud)

要取消绑定所有单击处理程序并在此之后立即绑定自己的处理程序,您可以执行以下操作:

$('.some-selector').unbind('click').click(function(event) {
  // Your code goes here
});
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于使用jQuery绑定的事件(使用.bind.bind内部使用的任何jQuery方法).如果要从给定的元素集中删除所有可能的onclick事件,可以使用:

$('.some-selector')
  .unbind('click') // takes care of jQuery-bound click events
  .attr('onclick', '') // clears `onclick` attributes in the HTML
  .each(function() { // reset `onclick` event handlers
    this.onclick = null;
  });
Run Code Online (Sandbox Code Playgroud)


小智 7

我想提出一个想法,而不是同时删除所有事件(只是覆盖它们)。

如果您的新一个单一绑定事件(此处称为“单击”)特定于它绑定到的元素,那么我相信您可以通过stopPropagation()函数忽略任何其他事件。像这样

$("specific-selector").on("click", ".specific-class", function (e) {
  e.stopPropagation()
  // e.stopImmediatePropagation()
  /* your code continues ... */
});
Run Code Online (Sandbox Code Playgroud)

它将阻止事件冒泡,因此您的其他事件将不会触发。使用stopImmediatePropagation()可以防止其他事件像单击一样附加到相同的元素上。

例如,如果“ mouseleave”事件也绑定到$(“ specific-selector .specific-class”)元素,则它也不会触发。

最后,所有其他事件都不会在此元素上触发,而是在您的新“ click”元素上触发。

未解决的问题是,如果其他事件也使用stopPropagation()怎么办?...然后,我认为规格最好的那个胜出,所以尽量避免复杂,太多的事件。

您可以在jQuery网站上看到“直接事件和委托事件”,以了解更多信息。