点击后jQuery会阻止其他事件

时间:2010-08-12 23:59:14

标签: jquery

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

我正在使用jQuery将点击事件绑定到按钮(jQuery UI)和图像链接(<a><img /></a>)。

是否有办法 - 一劳永逸地阻止其他事件在点击发生后触发?

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

由于

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

6 个答案:

答案 0 :(得分:32)

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

一种方法是在元素上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。

答案 1 :(得分:22)

event.preventDefaultevent.stopPropagation并返回false,如上所述。

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

答案 2 :(得分:8)

你看过preventDefault吗?

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

您还可以尝试stopImmediatePropagation()stopPropagation()


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

  

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

答案 3 :(得分:3)

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

答案 4 :(得分:2)

你有几个选择:

  1. 如果您的按钮/链接将重新加载 页面,你可以简单解开 click事件处理程序:

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

    $('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');
    })
    

    我认为这不适用于链接。

答案 5 :(得分:2)

另一种方法是使用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
});

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

相关问题