如何在不实际禁用按钮的情况下临时禁用按钮的单击事件? [英] How can I temporarily disable click events on a button without actually disabling it?

查看:122
本文介绍了如何在不实际禁用按钮的情况下临时禁用按钮的单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery,而无需更改给定按钮的disabled属性,为此禁用所有单击事件.

Using jQuery, I would like to, without changing the disabled attribute of a given button, disable all click events for it.

我当时正在考虑获取click事件处理程序,将其取消绑定并存储(例如,使用data()).

I was thinking of retrieving the click event handlers, unbind them, and storing them (say, using data()).

然后,一旦再次启用该按钮,我就可以重新绑定它们.

Then I can re-bind them once the button is enabled again.

推荐答案

这并不难,因为jQuery已经将其所有事件处理程序存储为data()在元素本身上.您可以通过.data().events获取(并修改)此对象.

Not hard to do since jQuery already stores all of its event handlers as data() on the element itself. You can get (and modify) this object through .data().events.

现在,您可以使用以下命令轻松保存对处理程序的引用:

Now you can easily save a reference to the handlers with:

 events._click = events.click;
 events.click = null;

然后使用以下方法还原它们:

And then restore them by using:

 events.click = events._click;
 events._click = null;

请注意,这不会禁用通过.delegate().live()绑定的事件,因为它们通过事件冒泡/传播进行工作.要同时禁用它们,只需绑定一个阻止传播到祖先元素的新处理程序:

Note that this won't disable events that are bound via .delegate() or .live(), as they work by event bubbling/propagation. To disable those as well, simply bind a new handler that blocks propagation to ancestor elements:

 events._click = events.click;
 events.click = null;
 // Block .live() and .delegate()
 $("#el").click(function (e) {
     e.stopPropagation();
 });

当需要再次启用处理程序时,您甚至不需要取消绑定此阻止程序功能,因为events.click = events._click将覆盖您与所有旧处理程序绑定的功能.

You don't even need to unbind this blocker function when it's time to enable the handlers again, since events.click = events._click will override the function you just bound with all the old handlers.

这篇关于如何在不实际禁用按钮的情况下临时禁用按钮的单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆