如何暂时禁用按钮上的点击事件而不实际禁用它?

使用jQuery,我想,在不更改给定按钮的disabled属性的情况下,禁用所有单击事件。

我正在考虑检索click事件处理程序,取消绑定它们并存储它们(例如,使用data() )。

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

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

$("#portalLink a").data().events.click = null 在控制台中 尝试 $("#portalLink a").data().events.click = null ,以禁用此页面左上角的“StackExchange”下拉列表。

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

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

然后使用以下命令恢复它们:

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

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

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

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

这是另一种方式:

 $("#myButton").click(function() { if ($(this).attr("temp_disable") == "disabled") { //nothing to do, temporarily disabled... } else { alert("You clicked me!"); } }); 

要“禁用”它10秒钟:

 $("#myButton").attr("temp_disable", "disabled"); window.setTimeout(function() { $("#myButton").attr("temp_disable", ""); }, 10000); 

现场测试案例: http : //jsfiddle.net/yahavbr/ByM6h/

这里的所有答案现在已经过时了 – 从jQuery 1.7开始,你应该使用官方jQuery网站上解释的.off()

     off demo        
Click!

您可以使用unbindbind

$('#control').unbind('click');

$('#control').bind('click', NameOfFunctionToCall);

这是要走的路。 如果您将onclick指定为属性,则可以切换属性总线

  $(button_element).attr('click', ''); 

  $(button_element).attr('click', 'do_the_regular_action()'); 

我将扩展Barry和Thariama提供的答案……我认为这将满足Ovesh的反对意见:

您可以为事件绑定添加命名空间。 这使您可以在以后引用该特定事件绑定,而不会与其他绑定发生冲突。 我认为这比接受的答案更清晰……(公平地说,在原始问题时,这可能不是jQuery中提供的)。

 // A generic click handler: $('.myButton').click(function() { ... }); // A namespaced click handler: $('.myButton').bind('click.someSituation', function() { ... }); // Later you can unbind only the handler you want by using the namespace: $('.myButton').unbind('click.someSituation'); // The default click handler still works. 

而不是做这件事使用Core Javascript来完成这个任务,例如看下面的例子。

 function MakeSaveDisabled(flg) { if (flg != null) { $(".btnpost").each(function () { this.removeAttribute("disabled"); if (this.hasAttribute("oclickevt")) { this.setAttribute("onclick", this.getAttribute("oclickevt")); } }); } else { $(".btnpost").each(function () { this.setAttribute("disabled", "true"); if (this.getAttribute("onclick") != null) { this.setAttribute("oclickevt", this.getAttribute("onclick")); } this.removeAttribute("onclick"); }); } } 

将javascript函数保存在某个临时属性中,并在需要时绑定它。