暂时禁止jQuery事件处理 [英] Suppress jQuery event handling temporarily

查看:90
本文介绍了暂时禁止jQuery事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种优雅的方法来临时禁止jQuery事件?我使用这样的代码:

Is there an elegant way to temporarily suppress jQuery events? I use code like this:

$(element).unbind(event, function1).unbind(event, function2);
// code for which the event is suppressed
$(element).bind(event, function1).bind(event, function2);

但是我发现它有点笨拙,并且不能很好地扩展到许多事件.为什么我要暂时取消事件?我使用BlockUI插件在Ajax访问期间阻止UI.这是通过BlockUI提出的 $().ajaxStart($.blockUI).ajaxStop($.unblockUI)完成的.

but I find it a bit clumsy and not very scalable to many events. Why do I want to suppress events temporarily? I use BlockUI plugin to block UI during Ajax access. This is done with: $().ajaxStart($.blockUI).ajaxStop($.unblockUI) as proposed by BlockUI.

但是,一个Ajax访问是特殊的,因此我需要另外一条消息. ajaxStart和ajaxStop事件会干扰消息代码(未显示任何内容):

However, one Ajax access is special, so I need a different message. The ajaxStart and ajaxStop events interfere with the message code (nothing is shown):

function message(text, callback) {
  if (text == undefined) {
     $.unblockUI();
     return;
  }

  // $().unbind('ajaxStop', $.unblockUI).unbind('ajaxStart', $.blockUI);
  $("#message_text").html(text);
  $.blockUI({message: $("#message")});
  $("#message_ok").click(function() { 
    // $().bind('ajaxStop', $.unblockUI).bind('ajaxStart', $.blockUI);
    $.unblockUI();
    if (callback != undefined) callback();
  });
}

仅当我取消注释unbind()和bind()行时,它才起作用.

Only if I uncomment the unbind() and the bind() lines, it is working.

推荐答案

我意识到这个问题很旧,但是我在寻找同一问题的答案时发现了它,最终找到了一种在简单应用程序中很好用的解决方案事件处理程序.

I realize this question is old, but I found it while seeking an answer to the same question, and ended up finding a different solution that works well in simple applications of event handlers.

$(element).click(function(e) {
  e.preventDefault();

  // Check for fired class
  if ($(this).hasClass('fired') == false) {
     // Add fired class to all instances of element
     $(element).addClass('fired');

     // Do the rest of the function...

     // Remove fired class to 'reactivate' events
     $(element).removeClass('fired');   
  }
}

在触发事件的代码时,只需在您的元素"中添加一个类,就可以防止由于另一个click事件而导致进一步的代码执行.因此,虽然您实际上并没有阻止任何其他点击事件,但是却阻止了结果代码的运行.简单粗暴,忽略了传教士大量使用bind和unbind的方法,但是行得通.

Simply adding a class to your 'element's while the code from the event is firing allows you to prevent further code from being executed as the result of another click event. So while you're not actually preventing any other click events, you're preventing the resulting code from running. Simple, crude, ignores the heavily preached use of bind and unbind, but works.

这篇关于暂时禁止jQuery事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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