jQuery的 - 我如何暂时禁用onclick事件侦听器的事件已被解雇后? [英] jQuery - How can I temporarily disable the onclick event listener after the event has been fired?
问题描述
我如何可以暂时禁用onclick事件监听器,(jQuery的preferred),该事件已被解雇后?
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
});
}
});
感谢了很多,
Thanks a lot,
阿尔
推荐答案
有很多方法可以做到这一点。例如:
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);
});
}
我们也可以使用事件代表团更清晰code和更好的性能:
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");
});
});
如果我们不需要重新启用处理程序已经执行完毕,那么我们就可以使用。一()
方法。它结合处理程序只执行一次。见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屋!