表单上有两个Submit事件处理程序.一个必须停止另一个 [英] Two submit event handlers on a form. One must stop the other

查看:89
本文介绍了表单上有两个Submit事件处理程序.一个必须停止另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将事件处理程序附加到表单.如果不满足条件,则第一个触发的事件应停止其他事件.

I have to event handlers attached to a form. The first one that fires should stop the other event if a condition is not met.

下面的代码不起作用,因为两个事件都将被触发.你能帮我吗?

The code below does not work, as both events will be triggered. Can you help me?

谢谢!

//fires first
$("#myform").submit(function(){
  if (some validation) {
    alert("You need to make the form valid");
    return false;
  }
});
//fires second
$("#myform").submit(function(){
  //ajax stuff
  return false;
});

p.s.我必须这样做,因为ajax的东西在一个不可更改的插件中.我不能避免两个事件处理程序

p.s. I have to this as the ajax stuff is in a plugin that is not changeable. I cannot avoid two event handlers

推荐答案

看看 event.stopImmediatePropagation() :

使其余处理程序不被执行,并防止事件使DOM树冒泡.

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

$("#myform").submit(function(event){
  if (some validation) {
    event.stopImmediatePropagation();
    alert("You need to make the form valid");
    return false;
  }
});

您可能还想使用 event.preventDefault() .

You might also want to use event.preventDefault().

更新:只需澄清一下:您可以依赖事件处理程序的调用顺序.通过jQuery的 bind 方法:

Update: Just to clarify: You can rely on the order the event handlers are called. From jQuery's bind method:

当事件到达元素时,将触发绑定到该事件类型的所有处理程序. 如果注册了多个处理程序,它们将始终按照绑定的顺序执行.所有处理程序执行完毕后,事件将沿着正常事件传播路径继续进行.

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

该顺序可能未在W3C的原始定义中定义,但可与jQuery一起使用.否则,上面命名的函数还是不必要的;)

The order might not be defined in W3C's original definition but it works with jQuery. Otherwise, the above named function would be unnecessary anyway ;)

这篇关于表单上有两个Submit事件处理程序.一个必须停止另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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