27

假设整个站点中有大量​​元素绑定了未知数量和类型的事件。

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

我会将事件绑定到单击事件处理程序,并且我正在使用 jQuery。

提前致谢。

4

4 回答 4

56

你正在寻找jQuery#unbind.

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

$('.some-selector').unbind();

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

$('.some-selector').unbind('click');

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

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

请注意,这仅适用于使用 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;
  });
于 2011-01-11T15:10:28.020 回答
8

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

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

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

它将阻止事件冒泡,因此您的其他事件不会触发。使用 stopImmediatePropagation() 来防止附加到与“click”相同的元素上的其他事件。

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

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

未解决的问题是,如果其他事件也使用 stopPropagation() 怎么办?...然后我认为具有最佳规范的获胜,所以尽量避免复杂的,太多的事件是最终的建议。

您可以在jQuery 网站上查看“直接和委托事件”以获取更多信息。

于 2013-12-31T09:09:19.717 回答
1

Try to use live instead of bind. Then you can easily remove live binding with die from selector which is fast operation and set another live equally fast.

   $('selection here').live('..', .....);  // multiple invocations
   $('selection here').die();
   $('selection here').live('click',.....);

DOM is not touched at all. Event condition is evaluated on event occurrence.

But generally if you just want to swap handler functions why not to do it this way:

var ahandler = function(evt) { /* first implementation */ }
$('.selector').bind('click', function(evt) { ahandler(evt); });

//and then if you want to change handlers
ahandler = function(evt) { /* new implementation */ };

This gives absolutely no cost of any changes, rebinding etc.

于 2011-01-11T15:12:45.223 回答
1

看起来这实际上很简单:

$('#foo').unbind('click');
$('#foo').bind('click', myNewFunction);

不过感谢您的回复。

于 2011-01-11T15:16:36.437 回答