jQuery 1次点击后禁用jquery功能,防止多次执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6064232/
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-26 20:20:25  来源:igfitidea点击:

Disable jquery function after 1 click, to prevent multiple executions

jquery

提问by lonesomeday

I have the following function which fetches more comments beyond the 20 that are shown by default

我有以下功能,可以获取默认显示的 20 条以外的更多评论

$('.more_comments_link').live('click', function() {
        $(".more_comments_link").text("Fetching More Comments ...");

        var ajaxOpts = {
            type: "get",
            url: "ajax_getcomments.php",
            dataType: 'json',
            data: "&itemid=<? echo $id; ?>&type=1&owner=<? echo $event["data"]["e_creator"]; ?>&more=1",
            success: function(data) {
                $('.discussion-more').after(data);
                $(".discussion-more").hide();
            }
        };

        $.ajax(ajaxOpts);
        return false;
    }); 

it works, the only problem is, the user can click the button 3 times really quickly, and it will send 3 requests to ajax_getcomments.php, getting the same result set every time.

它有效,唯一的问题是,用户可以非常快速地单击按钮 3 次,它将向 ajax_getcomments.php 发送 3 个请求,每次都获得相同的结果集。

i tried adding

我尝试添加

$(".more_comments_link").unbind('click');

but it doesn't do anything.

但它没有做任何事情。

The initial result set is fetched with jquery also, hence Im using .live(click'

初始结果集也是用 jquery 获取的,因此我使用 .live(click'

not sure if it has anything to do with why its not working.

不确定它是否与为什么它不起作用有关。

回答by lonesomeday

livedoesn't work with unbind-- you need dieinstead.

live不适用于unbind- 你需要die

Howeverthere is a better solution. Since you probably want to be able to update the content more than once, you can set a variable to see whether a request is currently running:

然而,有一个更好的解决方案。由于您可能希望能够多次更新内容,您可以设置一个变量来查看请求当前是否正在运行:

var requestRunning = false;
$('.more_comments_link').live('click', function () {
    if (requestRunning) { // don't do anything if an AJAX request is pending
        return;
    }

    $(".more_comments_link").text("Fetching More Comments ...");

    var ajaxOpts = {
        type: "get",
        url: "ajax_getcomments.php",
        dataType: 'json',
        data: "&itemid=<? echo $id; ?>&type=1&owner=<? echo $event["
        data "]["
        e_creator "]; ?>&more=1",
        success: function (data) {
            $('.discussion-more').after(data);
            $(".discussion-more").hide();
        },
        complete: function() {
            requestRunning = false;
        }

    };

    requestRunning = true;
    $.ajax(ajaxOpts);
    return false;
});

回答by Mike Barwick

All of these solutions are far to complex for a very simple solution; use .one() as per the documentation here:

对于一个非常简单的解决方案来说,所有这些解决方案都非常复杂。根据此处的文档使用 .one() :

http://api.jquery.com/one/

http://api.jquery.com/one/

Simply change liveto one. See below:

只需更改liveone. 见下文:

$('.more_comments_link').one('click', function() {

回答by Rob

You can use .die()to unbind .live()events.

您可以使用.die()解除绑定.live()事件。

Or set a flag elsewhere that says the request is in progress and check that at the beginning of the click handler.

或者在别处设置一个标志,表示请求正在进行中,并在点击处理程序的开头检查。

回答by Clamorious

You can use:

您可以使用:

$('element').off()

This will disable any event of your component that you are listening

这将禁用您正在侦听的组件的任何事件

回答by silent1mezzo

Try using the disabled keyword. This way you don't have to unbind the function, you just disable it from being pressed:

尝试使用 disabled 关键字。这样您就不必取消绑定该功能,您只需禁用它被按下:

$('.more_comments_link').live('click', function() {
    $(this).attr("disabled", true);
    $(".more_comments_link").text("Fetching More Comments ...");

    var ajaxOpts = {
        type: "get",
        url: "ajax_getcomments.php",
        dataType: 'json',
        data: "&itemid=<? echo $id; ?>&type=1&owner=<? echo $event["data"]["e_creator"]; ?>&more=1",
        success: function(data) {
            $('.discussion-more').after(data);
            $(".discussion-more").hide();
        }
    };

    $.ajax(ajaxOpts);
    return false;
}); 

回答by quasistoic

Depending on your use case, you might not have to use live, in which case onewould do exactly what you want it to do.

根据你的使用情况,您可能没有使用现场,在这种情况下一个会做的正是你想要它做什么。

回答by daryl

$('.more_comments_link').live('click', function(e) {

    if($(e.target).data('oneclicked')!='yes') {

        $(this).text("Fetching More Comments ...");

        var ajaxOpts = {
            type: "get",
            url: "ajax_getcomments.php",
            dataType: 'json',
            data: "&itemid=<? echo $id; ?>&type=1&owner=<? echo $event["data"]["e_creator"]; ?>&more=1",
            success: function(data) {
                $('.discussion-more').after(data);
                $(".discussion-more").hide();
            }
        };

        $.ajax(ajaxOpts);
        return false;
    }

    $(e.target).data('oneclicked','yes');

}); 

回答by Manpreet

You Can use for a single click on a button over the webpage

您可以使用单击网页上的按钮

 $('button id or classs').one('click',function(){    
 });

回答by Felipe Campanhol

For me this worked:

对我来说这有效:

$('.more_comments_link').live('click', function() {

if(e.handled !== true) // This will prevent event firing more than one time
{
  e.handled = true;
  //your code here...
}

});

回答by kxyz

My solution, working global on all ajax request, if is active request, new with the same url will be aborted. Working fine.

我的解决方案,在所有 ajax 请求上全局工作,如果是活动请求,则具有相同 url 的新请求将被中止。工作正常。

var activeRequests = [];

$(document).ajaxComplete(function(e, jqxhr, settings) {
    var i = activeRequests.indexOf(settings.url);
    if (i != -1) {

    setTimeout(function(){ activeRequests.splice(activeRequests.indexOf(settings.url), 1); }, 75);

}
});

$(document).ajaxSend(function(e, jqxhr, settings) {
var i = activeRequests.indexOf(settings.url)
if (i != -1) {
    jqxhr.abort();
    activeRequests.push(settings.url);
}
});