在执行功能时,jQuery会在单击后阻止其他事件

时间:2014-03-30 16:10:10

标签: jquery

我有两个a个链接.next-button-1.prev-button-1,当我点击按钮时会调用不同的函数

    $('.next-button-1').click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    gotoNext();
});

$('.prev-button-1').click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    gotoPrev();
});

执行每个功能需要一些时间。有没有办法让按钮在执行功能之前无法点击?

UPD
我找到了解决方案:

$('.next-button-1').click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    if ($(this).hasClass('disabled'))
        return false; 
     else {
        $(this).addClass('disabled');
        gotoNext();
    }
});

$('.prev-button-1').click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    if ($(this).hasClass('disabled'))
        return false; 
     else {
        $(this).addClass('disabled');
        gotoPrev();
    }
});

我删除了课程'disabled'
$('.next-button-1').removeClass('disabled');函数中的gotoNext()
$('.prev-button-1').removeClass('disabled');函数中的gotoPrev()

1 个答案:

答案 0 :(得分:1)

试试这个:

$('.next-button-1').click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).prop('disabled', true);
    gotoNext();
});

$('.prev-button-1').click(function (e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).prop('disabled', true);
    gotoPrev();
});

然后在函数末尾用$(your selector for the button).prop('disabled', false);重新启用它,这需要一些时间来执行。


修改

由于您的按钮为a标签,此解决方案无效。相反,您可以取消绑定并重新绑定您的事件处理程序,如下所示:

function nextHandler(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).unbind("click", nextHandler);
    gotoNext();
}

function prevHandler(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).unbind("click", prevHandler);
    gotoPrev();
}

$('.next-button-1').click(nextHandler);
$('.prev-button-1').click(prevHandler);

然后在慢速函数结束时使用$('.next-button-1').click(nextHandler);重新启用它们。为了清晰和统一,您可能希望使用$.bind("click", handler)而不是$.click(handler)

有关.bind()/.unbind() here.

的更多信息


更好的解决方案:

function nextHandler(e) {
    e.preventDefault();
    e.stopPropagation();
    gotoNext();
}

function prevHandler(e) {
    e.preventDefault();
    e.stopPropagation();
    gotoPrev();
}

$('.next-button-1').one('click', nextHandler);
$('.prev-button-1').one('click', prevHandler);

然后在你的慢功能结束时添加:$('.next-button-1').one('click', nextHandler);(当然是相同的形式)。

有关.one() here.

的更多信息