jQuery:停止提交表单,执行脚本,继续提交表单吗?

问题描述

| 我有一个表格,当我提交他时,我将执行多个脚本。这是我的代码
$(\"#RequestCreateForm\").submit(function (e) {
    if ($(\"#RequestCreateForm\").validate().checkForm() == false) { return; }

    e.preventDefault();

    //many scripts

    //How to continue submitting?
}
是否可以在
//many scripts
之后继续提交表单(以
e.preventDefault();
停止)? 谢谢     

解决方法

$(\"#RequestCreateForm\").submit(function (e) {
    if ($(\"#RequestCreateForm\").validate().checkForm() === false) { 
       e.preventDefault(); 
       //form was NOT ok - optionally add some error script in here

       return false; //for old browsers 
    } else{
       //form was OK - you can add some pre-send script in here
    }

    //$(this).submit(); 
    //you don\'t have to submit manually if you didn\'t prevent the default event before
}
    ,当您调用
$(\"#RequestCreateForm\").submit()
时,脚本将再次运行事件处理程序,并导致无限循环(正如Koen在接受的答案的注释中指出的那样)。因此,您需要在提交之前删除事件处理程序:
$(\"#RequestCreateForm\").on(\'submit\',function (e) {
    e.preventDefault();
    // do some stuff,and if it\'s okay:
    $(this).off(\'submit\').submit();
});
最后一行必须在条件语句中,否则它将始终发生,并在顶部否定
e.preventDefault();
。     ,
$(\"#RequestCreateForm\").submit(function (e) {
    if ($(\"#RequestCreateForm\").validate().checkForm() == false) 
    { 
         e.preventDefault();
         return false; 
    }        

    //other scripts

}
    ,我猜这里的所有解决方案都太复杂或导致javascript错误,最简单明了的解决方案:
jQuery(\"#formid\").submit(function(e) {
        if( ! (/*check form*/)  ){  //notice the \"!\"
          e.preventDefault();
          //a bit of your code
        } //else do nothing,form will submit
}); 
    ,
$(\"#RequestCreateForm\").submit(function (e) {
    if ($(\"#RequestCreateForm\").validate().checkForm() == false) { return; }

    e.preventDefault();

    //many scripts

    // Bypass the jquery form object submit and use the more basic vanilla
    // javascript form object submit

    $(\"#RequestCreateForm\")[0].submit();

}
    ,为避免提交循环,应使用其他变量。
var codeExecuted = false;
$(\'#RequestCreateForm\').submit(function(e) {
    ...
    if(!codeExecuted){
        e.preventDefault();
        ...
        functionExecuted = true;
        $(this).trigger(\'submit\');
    }
});
    ,这是我避免无限循环的方法。 在表单中,我使用带有ID(例如
<input type=\"button\" id=\"submit\" value=\"submit\"/>
)的\“ button \”来模仿Submit按钮; 在脚本中,我有这样的东西:
$(\'#submit\').click(function() {
  if(//validation rules is ok)
  {
      $(\"#RequestCreateForm\").submit(); //assuming the form id is #RequestCreateForm
  }
  else
  {
      return false;
  }
});
    ,返回;与e.preventDefault()相同; 尝试
$(\"#RequestCreateForm\").trigger(\'submit\');
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...