javascript form.submit() 方法中的 setTimeout 不起作用

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

setTimeout in form.submit() method does not work

javascriptjquery

提问by George Mickleburgh

I am trying setTimeout()function in form submit. However before executing the function the form gets submitted and anything inside the timeout function is not getting executed. Below is the code snippet.

我正在尝试setTimeout()表单提交中的功能。然而,在执行该函数之前,表单被提交并且超时函数中的任何内容都没有被执行。下面是代码片段。

$(window).load(function () {
     $("#myform").submit(function() {
          setTimeout(function(){
               alert("me after 1000 mili seconds");
               return false;              
          }, 1000);

    });
};

Kindly help me on how to resolve this issue...

请帮助我如何解决这个问题...

回答by karaxuna

$(window).load(function () {
     var submit = false;
     $("#myform").submit(function(e) {
          setTimeout(function(){
              alert("me after 1000 mili seconds");
              submit = true;
              $("#myform").submit(); // if you want            
          }, 1000);
          if(!submit)
              e.preventDefault();
     });
};

回答by BenM

The form is submitting straight away. You need to delegate the default action. This should work for you:

表单立即提交。您需要委托默认操作。这应该适合你:

$(window).load(function () {
     $("#myform").submit(function(e) {
          e.preventDefault();

          setTimeout(function(){
              alert("me after 1000 mili seconds");
          }, 1000);
    });
});

Please see this jsFiddle demo.

请参阅此jsFiddle 演示

回答by George Mickleburgh

If you want to disable the submit action on the form, you could try:

如果您想禁用表单上的提交操作,您可以尝试:

$(window).load(function () {
     $("#myform").submit(function(e) {
          e.preventDefault();
          setTimeout(function(){
          alert("me after 1000 mili seconds");
          return false;

        }, 1000);

    });
});

回答by Devang Rathod

First of all you forgotten closing brace )in last line

首先你忘记)了最后一行的大括号

$(window).load(function () {
     $("#myform").submit(function(e) {
          e.preventDefault();
          setTimeout(function(){
          alert("me after 1000 mili seconds");
          return false;

        }, 1000);

    });
});
 ^---- here you forgotten to put brace.