ald*_*dux 37 javascript ajax jquery events onclick
事件被触发后,如何暂时禁用onclick事件监听器(jQuery首选)?
例:
用户单击按钮并在下面触发此函数后,我想禁用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
});
}
});
Run Code Online (Sandbox Code Playgroud)
非常感谢,
阿尔
tho*_*rn̈ 66
有很多方法可以做到这一点.例如:
$(".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");
});
});
Run Code Online (Sandbox Code Playgroud)
要么
$(".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);
});
}
Run Code Online (Sandbox Code Playgroud)
我们还可以使用事件委派来获得更清晰的代码和更好的性能:
$(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");
});
});
Run Code Online (Sandbox Code Playgroud)
如果我们不需要在处理程序执行后重新启用它,那么我们就可以使用该.one()方法.它绑定仅执行一次的处理程序.请参阅jQuery文档:http://api.jquery.com/one
Ram*_*No5 19
您要在多长时间内禁用click事件侦听器?一种方法是使用jQuery的unbind http://docs.jquery.com/Events/unbind取消绑定事件监听器.
但最好的做法是不要将事件解除绑定只是为了以后重新绑定它.请改用布尔值.
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
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
编辑:为了安全起见,你也应该关心其他AJAX完成例程(只有三个:success,error,complete 看文档),否则active可能会留下假的.