jQuery - How can I temporarily disable the onclick event listener after the event has been fired?(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 事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:jQuery - 如何在事件触发后暂时禁用 onclick 事件侦


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01