我必须将事件处理程序附加到表单。如果不满足条件,第一个触发的应该停止另一个事件。
下面的代码不起作用,因为这两个事件都会被触发。你能帮帮我吗?
谢谢!
//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/