jQuery中的绑定事件总是在最后执行 [英] Binding event in jQuery to be executed always in the end

查看:120
本文介绍了jQuery中的绑定事件总是在最后执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将事件绑定到某个对象,并确保其中一个事件始终在最后执行?

Is there a way to bind events to some object, and ensure that one of those events will be executed always last?

  $('#something').bind('click', function () {
    // do something first
  });
  $('#something').bind('click', function () {
    // do this always last
  });  
  $('#something').bind('click', function () {
    // do this after first one
  });

谢谢!

推荐答案

这可能很有用,但可能无法满足OP的要求.在one上触发的处理程序未附加到当前处理程序队列的末尾,仅在后续事件上运行.

this can be useful but may not work as OP's question requires. The handler that fires on one does not get attached to the end of the current handler queue, it only runs on subsequent events.

对于将来的读者,您可以通过使用one()代理处理程序来实现.

For future readers, you can achieve this by proxying the handler using one().

$('.some-class').on('anevent', function(evt) {
    $(this).one(evt.type, function(evt) {
        //this code will fire after all other handlers for this event, except others that are proxied the same way
        console.log(evtO == evt, 'same event');
        if (evt.isDefaultPrevented())//can check signals to see whether you should still handle this event
            return;
        //do stuff last
    });
})

后来在其他地方:

$('.some-class').on('anevent', function(evt) {
    //do stuff first
    evt.preventDefault();//can signal to prevent the proxied function. could use evt.stopPropagation() instead
})

一个警告是,如果以后的处理程序使用return false;stopImmediatePropagation(),则与one()绑定的函数将在下次事件发生时首先触发 ,除非您明确取消绑定它以某种方式.

The one caveat is that if a later handler uses a return false; or stopImmediatePropagation(), the function bound with one() will fire first the next time that event occurs, unless you explicitly unbind it somehow.

这篇关于jQuery中的绑定事件总是在最后执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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