event.preventDefault() vs. return false vs Event.stopPropagation() 和其他方法

event.preventDefault() vs. return false vs Event.stopPropagation() and other methods

我正在使用表单并提交 $(document).on('submit','form',function(event){

现在我想停止提交表单以进行验证。我找到的选项是

event.preventDefault()
Event.stopPropagation()
return false
throw new Error("Something went badly wrong!");
calling a fake function which does not exist

有人能解释一下我应该使用哪一个吗?还有更多方法可以停止执行 Javascript 表单提交吗?

概要:

  • 如果您想阻止事件的默认(在本例中,提交表单),您可以使用event.preventDefault()
  • 您可以使用 return false (in a jQuery event handler like yours) if you want to both prevent the default and stop propagation of the event to ancestor elements. (Note that that's different from what return false means in native event handling, as I cover in this blog post。)
  • 使用event.stopPropagation()(而不是Event.stopPropagation()根本不会阻止默认操作:表单仍然会被提交。
  • 从处理程序中抛出错误不会阻止事件的默认操作。
  • 调用一个不存在的函数只是抛出一个错误,见上文。