点击后jQuery会阻止其他事件

我试图阻止链接和项目的多次点击,这会导致问题。

我使用jQuery将点击事件绑定到按钮(jQuery UI)和图像链接( )。

有没有办法做到 – 一劳永逸地阻止其他事件在点击发生后触发?

或者我是否必须维护一个名为_isProcessing的全局变量,并为每个事件处理程序将其设置为true?

谢谢

编辑:(澄清)感谢您的回答,我的问题不是阻止事件的冒泡,而是防止多次并发点击。

有多种方法可以防止并发点击运行代码。

一种方法是在元素上unbind('click') ,然后在准备好时再次unbind('click') .bind()

我宁愿使用某种旗帜。 它可能是一个变量,但我宁愿为该元素分配一个类,比如.processing ,并在完成后删除它。 因此,您可以让处理程序检查该类是否存在,以确定应运行的代码。

 $('someElement').click(function() { var $th = $(this); if($th.hasClass('processing')) return; $th.addClass('processing'); // normal code to run // then when done remove the class $th.removeClass('processing'); }); 

另一种选择是使用元素.data()来设置类似的标志,如$(this).data('processing', true); 完成后将其设置为false。

有event.preventDefault , event.stopPropagation并返回false, 如前所述 。

 $("a").click(function(e) { e.preventDefault(); e.stopPropagation(); return false; } 

你看过preventDefault吗?

 $("a").click(function(e) { e.preventDefault(); } 

你也可以尝试stopImmediatePropagation()stopPropagation()


您还可以查看one()事件。

将处理程序附加到元素的事件。 每个元素最多执行一次处理程序。

从事件处理程序返回false ,或在每个处理程序中调用ev.stopPropagation()

你有几个选择:

  1. 如果您的按钮/链接将重新加载页面,您可以简单地取消绑定click事件处理程序:

     $('input:submit').click(fumction() { $(this).unbind('click'); // Handle event here }) 
  2. 您可以禁用这些按钮,并在完成后重新启用它们(我认为这也适用于 ):

     $('input:submit').click(function() { $(this).attr('disabled', 'disabled'); // It also helps to let the user know what's going on: $(this).val('Processing...'); // Handle event here $(this).removeAttr('disabled'); }) 

    我认为这不适用于链接。

另一种方法是使用event.stopPropagation()和event.isPropagationStopped()进行信令:

例:

 $(button).click(function(e){ if(e.isPropagationStopped()) return; // propagation was stopped, so stop further execution // if you got this far - this event handler was called first // custom logic goes here // stop event propagation to signal other handlers e.stopPropagation(); // if you need, call e.preventDefault() to prevent default behaviour }); 

对其他事件处理程序重复相同的逻辑。