Javascript jQuery - 如何在触发事件后暂时禁用 onclick 事件侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1921855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:54:40  来源:igfitidea点击:

jQuery - How can I temporarily disable the onclick event listener after the event has been fired?

javascriptjqueryajaxeventsonclick

提问by aldux

How can I temporarily disable the onclick event listener, (jQuery preferred), after the event has been fired?

在触发事件后,如何暂时禁用 onclick 事件侦听器(首选 jQuery)?

Example:

例子:

After the user clicks on the button and fires this function below, I want to disabled the onclick listener, therefore not firing the same command to my django view.

在用户单击按钮并在下面触发此函数后,我想禁用 onclick 侦听器,因此不会向我的 django 视图触发相同的命令。

$(".btnRemove").click(function(){
   $(this).attr("src", "/url/to/ajax-loader.gif");
   $.ajax({
        type: "GET",
        url: "/url/to/django/view/to/remove/item/" + this.id,
        dataType: "json",
        success: function(returned_data){
            $.each(returned_data, function(i, item){
              // do stuff                       
     });
   }
});

Thanks a lot,

非常感谢,

Aldo

奥尔多

回答by thorn?

There are a lot of ways to do it. For example:

有很多方法可以做到。例如:

$(".btnRemove").click(function() {
    var $this = $(this);
    if ($this.data("executing")) return;
    $this
        .data("executing", true)
        .attr("src", "/url/to/ajax-loader.gif");
    $.get("/url/to/django/view/to/remove/item/" + this.id, function(returnedData) {
        // ... do your stuff ...
        $this.removeData("executing");
    });
});

or

或者

$(".btnRemove").click(handler);

function handler() {
    var $this = $(this)
        .off("click", handler)
        .attr("src", "/url/to/ajax-loader.gif");
    $.get("/url/to/django/view/to/remove/item/" + this.id, function(returnedData) {
        // ... do your stuff ...
        $this.click(handler);
    });
}

We can also use event delegation for clearer code and better performance:

我们还可以使用事件委托来获得更清晰的代码和更好的性能:

$(document).on("click", ".btnRemove:not(.unclickable)", function() {
    var $this = $(this)
        .addClass("unclickable")
        .attr("src", "/url/to/ajax-loader.gif");
    $.get("/url/to/django/view/to/remove/item/" + this.id, function(returnedData) {
        // ... do your stuff ...
        $this.removeClass("unclickable");
    });
});

If we don't need to re-enable the handler after it has been executed, then we can use the .one()method. It binds handlers that are to be executed only once. See jQuery docs: http://api.jquery.com/one

如果我们不需要在处理程序执行后重新启用它,那么我们可以使用该.one()方法。它绑定只执行一次的处理程序。请参阅 jQuery 文档:http: //api.jquery.com/one

回答by RamboNo5

For how long do you want to disable the click event listener? One way is to unbind the event listener using jQuery's unbindhttp://docs.jquery.com/Events/unbind.

您要禁用单击事件侦听器多长时间?一种方法是使用 jQuery 的unbindhttp://docs.jquery.com/Events/unbind解除事件侦听器的绑定。

But it's best-practice not to unbind an event only to rebind it later. Use a boolean instead.

但最好的做法是不要解除绑定事件,然后再重新绑定它。改用布尔值。

var active = true;
$(".btnRemove").click(function() {
    if (!active) {
        return;
    }
    active = false;
    $(this).attr("src", "/url/to/ajax-loader.gif");
    $.ajax({
        type: "GET",
        url: "/url/to/django/view/to/remove/item/" + this.id,
        dataType: "json",
        success: function(returned_data) {
            active = true; // activate it again !
            $.each(returned_data, function(i, item) {
                // do stuff                       
            });
        }
    });
});

edit:to be safe you should also care about the other ajax completion routines (there are only three: success, error, completesee docs) or else activemight stay false.

编辑:为了安全起见,你也应该关心其他AJAX完成例程(只有三个:successerrorcomplete看文档),或者active威力逗留假。

回答by ram

why not disable the button ?Any specific reason that you want to disable this listner alone ? BTB, from your code, I see that you are making an ajax call. SO you specifically want to block user until the call comes back ? If yes, you can try blockUI, a jQuery plugin

为什么不禁用按钮?您想单独禁用此侦听器的任何具体原因?BTB,从您的代码中,我看到您正在进行 ajax 调用。所以你特别想阻止用户直到电话回来?如果是,您可以尝试使用 jQuery 插件blockUI

回答by Josh Stodola

I would setup a global variable to keep track of AJAX requests...

我会设置一个全局变量来跟踪 AJAX 请求......

var myApp = {
  ajax: null
}

And then have this little bit of magic to stop simultaneous requests...

然后有一点点魔法来阻止同时请求......

// Fired when an AJAX request begins
$.ajaxStart(function() { myApp.ajax = 1 });

// Fired when an AJAX request completes
$.ajaxComplete(function() { myApp.ajax = null });

// Fired before an AJAX request begins
$.ajaxSend(function(e, xhr, opt) {
  if(myApp.ajax != null) {
    alert("A request is currently processing. Please wait.");
    xhr.abort();
  }
});

With this approach, you should not have to go back through your code and modify every single one of your AJAX calls. (something I call an "append" solution)

使用这种方法,您不应该返回代码并修改每一个 AJAX 调用。(我称之为“附加”解决方案)

回答by Mariano Cavallo

I would use a class eg 'ajax-running'. The click event would only be executed if the clicked element does not have the 'ajax-running' class. As soon you ajax call finishes you can remove the 'ajax-running' class so it can be clicked again.

我会使用一个类,例如'ajax-running'。只有当被点击的元素没有 'ajax-running' 类时,才会执行点击事件。ajax 调用完成后,您可以删除“ajax-running”类,以便再次单击它。

$(".btnRemove").click(function(){
    var $button         = $(this);
    var is_ajaxRunning  = $button.hasClass('ajax-running');
    if( !is_ajaxRunning ){
        $.ajax({
            ...
            success: function(returned_data) {
                ...
                $button.removeClass('ajax-running');
            });
        };
    }   
});

回答by Sampson

You could make the action within the click based upon a boolean value. When it's clicked, change the boolean value and uset setTimeout() to change it back after a few seconds. That would effectively limit the user to clicking the button only once every few seconds.

您可以根据布尔值在点击中执行操作。单击它时,更改布尔值并在几秒钟后使用 setTimeout() 将其更改回来。这将有效地限制用户每几秒钟只点击一次按钮。

var isEnabled = true;

$("a.clickMe").click(function(e){
  e.preventDefault();
  if (isEnabled == true) {
    isEnabled = false; // disable future clicks for now
    do_Something();
    setTimeout(function(){
      isEnabled = true;
    }, 3000); // restore functionality after 3 seconds
  }
});

回答by jitter

var ajaxAction = function() {
    var ele = $(this);
    ele.unbind("click", ajaxAction);
    ele.attr("src", "/url/to/ajax-loader.gif");
    $.ajax({
        type: "GET",
        url: "/url/to/django/view/to/remove/item/" + this.id,
        dataType: "json",
        success: function(returned_data) {
            $.each(returned_data, function(i, item) {
            });
        },
        complete: function() {
            ele.bind("click", ajaxAction);
        }
    });
}
$(".btnRemove").click(ajaxAction);

回答by T.J. Crowder

I'd suggest disabling the button, then re-enabling it in your Ajax completion routines (success orfailure, remember). If you're worried about the browser not respecting your disabling the button, you can back that with your own flag on the button (e.g., set an attribute called data-disabled, using the data-prefix as good practice and to be HTML5 compatible). But barring actually running into a problems with browsers not disabling the button, I'd probably consider that good enough.

我建议禁用该按钮,然后在您的 Ajax 完成例程中重新启用它(成功失败,请记住)。如果您担心浏览器不尊重您禁用按钮,您可以在按钮上使用您自己的标志来支持它(例如,设置一个名为 的属性data-disabled,使用data-前缀作为良好做法并与 HTML5 兼容)。但是,除非实际遇到浏览器未禁用按钮的问题,否则我可能认为这已经足够了。

回答by sangam

If you are posting via ajax, you can disable the button on click and enable it after the process completes. But if you are posting back, you cannot just disable the button. Disabling the button causes the server side click event not to fire. So just hide the button on click and show user friendly message. The post on how to disable asp.net button on postbackhelps.

如果您通过 ajax 发布,您可以在单击时禁用该按钮并在该过程完成后启用它。但是,如果您要回发,则不能仅禁用该按钮。禁用该按钮会导致服务器端单击事件不触发。所以只需隐藏点击按钮并显示用户友好的消息。关于如何在回发时禁用 asp.net 按钮的帖子有帮助。

回答by jules345

you could also just hide the button (or the containing div)

您也可以隐藏按钮(或包含的 div)

$(".btnRemove").click(function() {
   $(this).hide();
   // your code here...
})

and you can just call .show() if you need to display it again.

如果您需要再次显示它,您可以调用 .show() 。

Also depending on your use case you should consider using a loading overlay instead

此外,根据您的用例,您应该考虑使用加载覆盖