开发者

Multiple concurrent event handling in jQuery

开发者 https://www.devze.com 2023-02-06 01:10 出处:网络
I am attempting to handle multiple concurrent events using jQuery but I am having problems finely managing when the events are fired.

I am attempting to handle multiple concurrent events using jQuery but I am having problems finely managing when the events are fired.

<html>
  <head>
  <title></title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  </head>
  <body>

    <div id="edit" contenteditable="true">Edit some content</div>
    <button id="button" type="button">Click the button</button>

    <script type="text/javascript">
      $(document).ready(function () {
        $('#button').click(function (e) {
          alert('I have been clicked.');
        });
        $('#edit').blur(function (e) {
          alert('I have been edited.')
        });
      });
    </script>

  </body>
</html>

What I wish to achieve is for the content of the DIV to be edited by a user and when the button is clicked, for that event to be raised before the blur event on the DIV. It may be the case that the button is never clicked in which case the blur event may fire on its own. As you can see using the code above, once you edit the content and click the button only the blur event is fired.

Please can someone advise开发者_Go百科 how I may achieve the desired functionality?


One — admittingly very hacky — way would look like this:

$(document).ready(function() {
    var buttonClicked = false;
    $('#button').bind('click', function(e) {
        buttonClicked = true;
        alert('I have been clicked.');
    });
    $('#edit').bind('blur', function(e) {
        setTimeout(function() {
            if (!buttonClicked) alert('I have been edited.');
            buttonClicked = false;
        }, 100);

    });
});

This example doesn't prevent the firing of the event, though. It only handles the callback.

Here it is working: http://jsfiddle.net/Dp6b5/1/ You can adjust the timeout delay and don't necessarily have to use bind in this case either.

It's an interesting question, but I don't see any "proper" way to handle this atm., since the blur event is de facto fired before the click. Maybe someone else has a better idea I can't see atm..

0

精彩评论

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