Jquery - 确保事件处理程序最后在处理程序链中执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3150841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery - Make sure event handler is last to be executed in chain of handlers
提问by Kyle
Is there a way to make sure the event handler you attach is the last in the chain of event handlers to be executed?
有没有办法确保您附加的事件处理程序是要执行的事件处理程序链中的最后一个?
I have an event handler that submits a form by ajax, but at a later time, after I attach my ajax submitting handler, another handler is attached to the form to do validation logic. The validation logic should occur before the ajax submitting handler, but it doesn't since it was bound afterwards.
我有一个通过 ajax 提交表单的事件处理程序,但稍后,在我附加我的 ajax 提交处理程序后,另一个处理程序附加到表单上以执行验证逻辑。验证逻辑应该发生在 ajax 提交处理程序之前,但它没有发生,因为它是在之后绑定的。
Is there a way to make it so my ajax submitting handler always is the last handler in the chain of handlers to be executed, without changing the order in which the handlers are bound?
有没有办法让我的 ajax 提交处理程序始终是要执行的处理程序链中的最后一个处理程序,而无需更改处理程序的绑定顺序?
采纳答案by David Radcliffe
I don't think there is a way to manipulate the order directly.
我认为没有办法直接操纵订单。
Take a look at this: How to order events bound with jQuery
回答by Pedro Pinheiro
My solution (http://jsfiddle.net/968jj/1345/) :
我的解决方案(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);
}
}
}
usage:
用法:
$(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);
});
With some HTML
带有一些 HTML
<div id="el"></div>
<div id="el"></div>
and some CSS
和一些 CSS
div { width: 200px; height: 200px; background-color: red; }
div { 宽度:200px; 高度:200px;背景颜色:红色;}
You can use it with any one or more than one event:
您可以将它用于任何一个或多个事件:
$("#el").lastHandler('keypress keyup change',fnHandler);
$("#el").lastHandler('click mouseover',fnHandler);