单击1次后禁用jquery功能,以防止多次执行 [英] Disable jquery function after 1 click, to prevent multiple executions
问题描述
我具有以下功能,该功能可获取默认显示的20条以上的更多评论
I have the following function which fetches more comments beyond the 20 that are shown by default
$('.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;
});
它有效,唯一的问题是,用户可以非常快地单击按钮3次,它将向ajax_getcomments.php发送3个请求,每次都得到相同的结果集.
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.
我尝试添加
$(".more_comments_link").unbind('click');
但是它什么也没做.
初始结果集也通过jquery获取,因此Im使用.live(click'
The initial result set is fetched with jquery also, hence Im using .live(click'
不确定它是否与为什么不起作用有关.
not sure if it has anything to do with why its not working.
推荐答案
live
与unbind
不兼容-您需要 die
代替.
live
doesn't work with unbind
-- you need die
instead.
但是有一个更好的解决方案.由于您可能希望能够多次更新内容,因此可以设置变量以查看请求当前是否正在运行:
However there 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;
});
这篇关于单击1次后禁用jquery功能,以防止多次执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!