jQuery - 如何在触发事件后暂时禁用 onclick 事件侦听器? [英] jQuery - How can I temporarily disable the onclick event listener after the event has been fired?

查看:30
本文介绍了jQuery - 如何在触发事件后暂时禁用 onclick 事件侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例:

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

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.

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

非常感谢,

奥尔多

推荐答案

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

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");
    });
});

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

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

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

这篇关于jQuery - 如何在触发事件后暂时禁用 onclick 事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆