Javascript 在 addEventListener 上返回 false 提交仍然提交表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4924036/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:47:43  来源:igfitidea点击:

return false on addEventListener submit still submits the form?

javascriptjavascript-events

提问by David

var form = document.forms[0]; 
form.addEventListener("submit", function(){
  var email = form.elements['answer_13829'].value;
  if( email == '[email protected]') {
     alert('redirecting the user...');
     window.location = 'xxxx';
     return false;
  }
});

I don't understand - it still submits the form. Can someone patch my code and make it work?

我不明白 - 它仍然提交表单。有人可以修补我的代码并使其工作吗?

回答by Tim Down

You need to use the preventDefault()method of the event object.

您需要使用preventDefault()事件对象的方法。

Note that neither addEventListener()nor preventDefault()are supported in IE <= 8.

请注意,IE <= 8既不支持addEventListener()也不preventDefault()支持。

var form = document.forms[0]; 
form.addEventListener("submit", function(evt){
  var email = form.elements['answer_13829'].value;
  if( email == '[email protected]') {
     evt.preventDefault();
     alert('redirecting the user...');
     window.location = 'xxxx';
  }
});

回答by RelicOfTesla

the return false;it's work on jQuery bind function only

return false;它的只有jQuery的绑定功能工作