开发者

Prevent queued events from being executed in jQuery

开发者 https://www.devze.com 2023-01-14 22:06 出处:网络
I have a handler which is triggered for two events: blur trigger of object A. click on object B. The problem is when Object A has focus and I click on B, both the events are triggered. I want to sto

I have a handler which is triggered for two events:

  1. blur trigger of object A.
  2. click on object B.

The problem is when Object A has focus and I click on B, both the events are triggered. I want to stop this from happening. The handler should be executed only once in this case because there's a toggle() inside which is being nullified due to the second call. Is there any way I can clear all pending events on an object?

<div id='panel'>Hey!</div>    

<input type='text' id='a'>
<div id='b'>Hello</div>

function handler() {
    $('#panel').toggle();
}

$('#a').blur(handler);
$('#b').click(handler);

When the textbox has the focus and the user clicks on the div 'b', two events are triggered - blur of input a and click of div b. Both the events are handled by the same function and since the function incidentally toggles another element (panel), the functionality fails since the two toggles cancel each other out. So, what I need is a a way to cle开发者_运维百科ar out all pending events for an element.


You may be looking for event.preventDefault():

If this method is called, the default action of the event will not be triggered.

Or, maybe you need to .unbind() one event, then rebind it after the other event has fired.

.undelegate() may do what you're after:

Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.


Use event.stopImmediatePropagation() in the event handler.

Description: Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

Documentation: http://api.jquery.com/event.stopImmediatePropagation/


What if you keep track of the events firing, and block the toggle from being called if the other has already been called?

var called = false;

function handler() {
   if (!called) {
      called = true;
      $('#panel').toggle(1, function () { // change the duration to your liking
          called = false;
      });
   }
}

$('#a').blur(handler);
$('#b').click(handler);

Haven't tested yet, but I believe this should work.

EDIT: It worked fine, but then again, when I tested the original handler I did not get the behavior you said you were getting -- the handler was only called once, even in the situation you described (focused input, click on "b"). I tested it in FF 3.6, IE8, and Chrome 5.

0

精彩评论

暂无评论...
验证码 换一张
取 消