jQuery - Off() 不工作取决于事件

jQuery - Off() not working depending of the event

我正在使用 "off event" 来避免多次 AJAX 请求(例如,如果用户进行多次点击)。完美运行。

问题是,根据 "on('click')" 事件的调用方式,事件 off() 根本不起作用。我举个例子:

函数:

var addComment(elem) = function(){
    $.ajax({
        type: "POST",
        url: '../../ajax/request.php',
        dataType: 'json',
        data: data,
        beforeSend: function(){
           // after this line, click the elem doesn't do anything
           elem.off('click');
        },
        success: function(result){
            if (result.success){
               console.log('success!');
            }else{
               console.log('no success...');
            }
            //making "elem" clickable again
            elem.on('click',function(){
                addComment(elem);
            });
        },
        error: function(xhr, ajaxOptions, thrownError){
            alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
        }
    });
}

事件:

// Using this, the off event works normally
$('.divArea button.newComment').on('click',function(){
    addComment($(this));
});

// Using this, the off event simply is not executed
$('.divArea')
    .on('click', 'button.newComment',function(){
        addComment($(this));
    })

为什么在第二种情况下,off() 不起作用以及我应该如何处理 off() 在两个事件调用示例中都能正常工作?

在此先致谢。

第二个版本不起作用的原因是当您使用委托时,事件绑定不在按钮上,它实际上是在 .divArea。委派的工作原理是让处理程序自动检查事件的目标是否与您委派给的选择器相匹配——这就是它能够扩展到在建立绑定时不存在的元素的方式。

由于单个元素没有绑定,您无法使用 .off 删除它们。

您可以做的是使用 class 委托给选择器,并在处理事件时更改 class。

$('.divArea').on('click', 'button.newComment:not(.handled)', function() {
    addComment($(this));
});

function addComment(elem) {
    $.ajax({
        type: "POST",
        url: '../../ajax/request.php',
        dataType: 'json',
        data: data,
        beforeSend: function(){
           // after this line, click the elem doesn't do anything
           elem.addClass("handled");
        },
        success: function(result){
            if (result.success){
               console.log('success!');
            }else{
               console.log('no success...');
            }
            //making "elem" clickable again
            elem.removeClass("handled");
        },
        error: function(xhr, ajaxOptions, thrownError){
            alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
        }
    });
}