jQuery 在表单提交之前执行操作?

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

Perform action before form submit?

jqueryforms

提问by Naftali aka Neal

I have this HTML form with an id and I have binded this id to the submit function. What I want is when a user clicks submit, a popup comes up like a modal box thanking them. And only after they click off the screen or when the modal box closes is when I want the form to submit and refresh the page.

我有一个带有 id 的 HTML 表单,并且我已将此 id 绑定到提交函数。我想要的是当用户点击提交时,弹出窗口就像一个模态框感谢他们。只有在他们点击屏幕后或模式框关闭时,我才希望表单提交并刷新页面。

But the way I have it now seems it will refresh no matter what. I am using the fancy popup plugin for the modal box.

但我现在拥有它的方式似乎无论如何都会刷新。我正在为模态框使用精美的弹出插件。

<form action="submit-comment.php" method="post" id="form">
<input type="text" name="comment" />
<input type="submit" name="submit" value="Submit" />
</form>

jQuery("#form").submit(function() {
     jQuery.fancybox('<div class="box">Some content</div>', {
           'onClosed' : function() { return true; }
            }     
     });
});

As you can see I am trying to tell it to return true only on close but it isn't really working.

正如你所看到的,我试图告诉它只有在关闭时才返回 true ,但它并没有真正起作用。

Any ideas?

有任何想法吗?

回答by Naftali aka Neal

Try this:

尝试这个:

jQuery("#form").submit(function(e) {
     var self = this;
     e.preventDefault();
     jQuery.fancybox('<div class="box">Some amazing wonderful content</div>', {
           'onClosed' : function() { 
                          self.submit();
                        }
     });
     return false; //is superfluous, but I put it here as a fallback
});

javascript is asynchronous so you cannot delay the return statement.

javascript 是异步的,因此您不能延迟 return 语句。



UPDATE

更新

To make it so that the code above works, change the nameof you submit button to something else, for example:

为了使上面的代码有效,name请将提交按钮更改为其他内容,例如:

<input type="submit" name="submit_me" value="Submit" />

回答by Radek Pech

(response to Rick's question under Neal's answer: "any other way? Because I don't have direct access to this html")

(在 Neal 的回答下回答 Rick 的问题:“还有其他方式吗?因为我无法直接访问此 html”)

If you, for some reason, need a submit button to have ID="submit" and cannot use form.submit method (because it links to "input[type=submit]#submit" button) you can do this:

如果您出于某种原因需要一个提交按钮来具有 ID="submit" 并且不能使用 form.submit 方法(因为它链接到“input[type=submit]#submit”按钮),您可以这样做:

$('<form>')[0].submit.call(form); //jQuery
//OR:
document.createElement('form').submit.call(form); //pure HTML w/o any framework

i.e. create new empty form and use its submit method to call it in scope of your own form

即创建新的空表单并使用其提交方法在您自己的表单范围内调用它