javascript - 表单上的两个提交事件处理程序。一个必须阻止另一个

标签 javascript jquery

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

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

谢谢!

//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;
});

附注我必须这样做,因为 ajax 的东西在一个不可更改的插件中。我无法避免两个事件处理程序

最佳答案

看看event.stopImmediatePropagation() :

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() .

更新: 澄清一下:您可以依赖事件处理程序的调用顺序。来自 jQuery 的 bind方法:

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。否则,上面命名的函数无论如何都是不必要的;)

关于javascript - 表单上的两个提交事件处理程序。一个必须阻止另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4507956/

相关文章:

javascript - WinJS.UI.ListView - 使用 JavaScript 构建模板时刷新项目

jquery - magento 使用 jquery 且无冲突

jQuery 和链接 anchor

javascript - 如何手动触发 webpack 开发服务器的监视/重新加载?

javascript - Cufon 文本 z-index(IE6 和 IE7 时尚的选择框错误)

javascript - 导航栏内容不会在移动 View 中加载

jquery - getJSON 填充下拉列表 MVC4

javascript - 意外的 token <reactjs应用程序中的bundle js

javascript - 使用 $.ajax 定位某个 PHP 函数

javascript - jquery on click事件不起作用