【问题标题】:Form Submitting Even Though I have a "return false"表单提交即使我有“return false”
【发布时间】:2016-10-31 12:39:30
【问题描述】:

我有一个按钮,点击时会调用 function1,而该按钮会调用另一个 function2。如果 function2 满足条件,它应该返回 false 并在那里死掉,但它会继续,返回到 function1,执行 function1 的其余部分并提交表单。我是 javascript 新手。

 <input type="button" value="Submit" onclick="function1()" />

 function function1() {
  function2();
  //execute rest of function
 }

 function2() {
 var this;
 var that;
 if(!this || !that) {
 alert("You did not fill out fields on the form under Tab1");
 return false;  //I thought it was supposed to stop here
 }
 } 

【问题讨论】:

  • 对不起,按钮点击的实际代码是:

标签: return-value onsubmit


【解决方案1】:

在函数1中,当你调用函数2时,如果你想让函数1在函数2返回false时停止,那么你必须在函数1内停止它,如下所示:

function function1() {
  // If function2 returns false, then stop function1
  if (!function2()) return;
  //execute rest of function
 }

 function2() {
  var this;
  var that;
  if(!this || !that) {
   alert("You did not fill out fields on the form under Tab1");
   return false;  //I thought it was supposed to stop here
  }
 } 

【讨论】:

  • +1,同意@Jayce444。除非您一直返回false,否则表单将提交。如果你只是将false返回给function1,你必须从那里处理它。
  • Jayce444,我试过了,if(!function2()) return;但什么也没发生。它从未提交数据
  • 我试过了,效果很好: if (function2() == false) { return false;但如果我能让它工作,你的方式似乎更短
  • 对不起,在我的代码中它应该是 'return false' 而不仅仅是 'return'
猜你喜欢
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
相关资源
最近更新 更多