2010-06-30 73 views
10

链要执行有没有一种方式,以确保您连接的事件处理程序中的事件处理程序链中最后一个被执行?jQuery的 - 确保事件处理程序是最后的处理程序

我有一个事件处理程序,通过AJAX提交表单,但在稍后的时间,当我附上我的ajax提交处理程序,另一个处理程序连接到形式做验证逻辑。验证逻辑应该发生在ajax提交处理程序之前,但是之后它不会被绑定。

是否有办法使它所以我的AJAX提交处理程序总是在处理程序链中的最后一个处理程序来执行,而不改变其处理程序绑定的顺序?

+0

你可以给一段代码? – dzida 2010-06-30 15:44:04

+0

看到类似的[问题](http://stackoverflow.com/questions/2360655/jquery-event-handlers-always-execute-in-order-they-were-bound-any-way-around-th/2641047# 2641047)。 – Anurag 2012-02-03 17:18:00

+0

我在[此问题]上发布了针对此问题的其他解决方案(http://stackoverflow.com/a/19674508/315024)。 – Walf 2013-10-30 05:32:16

回答

1

我的解决方案(http://jsfiddle.net/968jj/1345/):

$.fn.lastHandler = function (events, handler) { 
    var element = $(this); 
    events = events.split(' '); 
    for (var evt in events) { 
     var event = $(element).data("events")[events[evt]]; 
     var hsucess = null; 
     $.each(event, function (i, h) { 
      if (h.handler == handler) { 
       hsucess = h; 
      } 
     }); 
     var index = event.indexOf(hsucess); 
     if (index > -1) { 
      event.splice(index, 1); 
      event.push(hsucess); 
     } 
    } 
} 

用法:

$(function() { 

    var m1 = function(){ alert("mouseover to be the last"); }; 
    var m2 = function(){ alert("mouseover to be the first"); }; 
    var m3 = function(){ alert("mouseover to be the second"); }; 
    $("#el").mouseover(m1); 
    $("#el").mouseover(m2); 
    $("#el").mouseover(m3); 

    $("#el").lastHandler('mouseover',m1); 

}); 

随着一些HTML

< DIV ID = “埃尔“> < /格>

和一些CSS

DIV {宽度:200像素; height:200px;背景颜色:红色; }

你可以使用任何一个或多个事件中使用它:

$("#el").lastHandler('keypress keyup change',fnHandler); 
$("#el").lastHandler('click mouseover',fnHandler);