Javascript jQuery - 防止默认,然后继续默认
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14375144/
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
jQuery - prevent default, then continue default
提问by StackOverflowNewbie
I have a form that, when submitted, I need to do some additional processing before it should submit the form. I can prevent default form submission behavior, then do my additional processing (it's basically calling Google Maps API and adding a few hidden fields to the form) -- and then I need the form to submit.
我有一个表单,当提交时,我需要在提交表单之前做一些额外的处理。我可以阻止默认的表单提交行为,然后进行我的额外处理(它基本上是调用 Google Maps API 并向表单添加一些隐藏字段)——然后我需要提交表单。
Is there a way to "prevent default", then some point later "continue default?"
有没有办法“防止默认”,然后在某个时间点“继续默认”?
回答by Ron van der Heijden
When you bind the .submit()event to the form, and you do the things you want to do before returning (true), these things happen prior to the actual submission.
当您将.submit()事件绑定到表单,并且在返回之前执行您想做的事情 (true) 时,这些事情会在实际提交之前发生。
For example:
例如:
$('form').submit(function(){
alert('I do something before the actual submission');
return true;
});
Another example on jquery.com: http://api.jquery.com/submit/#entry-examples
jquery.com 上的另一个示例:http://api.jquery.com/submit/#entry-examples
回答by Aurel
Use jQuery.one()
用 jQuery.one()
Attach a handler to an event for the elements. The handler is executed at most once per element per event type
将处理程序附加到元素的事件。每个事件类型的每个元素最多执行一次处理程序
$('form').one('submit', function(e) {
e.preventDefault();
// do your things ...
// and when you done:
$(this).submit();
});
It does what you want and you don't need to worry about multiple submit.
它可以满足您的需求,您无需担心多次提交。
回答by bipen
I would just do:
我只会做:
$('#submiteButtonID').click(function(e){
e.preventDefault();
//do your stuff.
$('#formId').submit();
});
Call preventDefaultat first and use submit()function later, if you just need to submit the form
如果您只需要提交表单preventDefault,请先调用 ,然后使用submit()函数
回答by Joepreludian
Using this way You will do a endless Loop on Your JS. to do a better way you can use the following
使用这种方式你将在你的 JS 上做一个无限循环。要做得更好,您可以使用以下方法
var on_submit_function = function(evt){
evt.preventDefault(); //The form wouln't be submitted Yet.
(...yourcode...)
$(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
$(this).submit();
}
$('form').on('submit', on_submit_function); //Registering on submit.
I hope it helps! Thanks!
我希望它有帮助!谢谢!
回答by igorludi
This is, IMHO, the most generic and robust solution (if your actions are user-triggered, eg 'user clicks on a button'):
恕我直言,这是最通用和最强大的解决方案(如果您的操作是用户触发的,例如“用户点击按钮”):
- the first time a handler is called check WHO triggered it:
- if a user tiggered it - do your stuff, and then trigger it again (if you want) - programmatically
- otherwise - do nothing (= "continue default")
- 第一次调用处理程序时检查谁触发了它:
- 如果用户触发它 - 做你的事情,然后再次触发它(如果你愿意) - 以编程方式
- 否则 - 什么都不做(=“继续默认”)
As an example, note this elegant solution to adding "Are you sure?" popup to any button just by decorating a button with an attribute. We will conditionally continue default behavior if the user doesn't opt out.
例如,请注意添加“您确定吗?”的优雅解决方案。只需使用属性装饰按钮即可弹出任何按钮。如果用户不选择退出,我们将有条件地继续默认行为。
1. Let's add to every button that we want an "are you sure" popup a warning text:
1. 让我们为每个我们想要“你确定”弹出的按钮添加一个警告文本:
<button class="btn btn-success-outline float-right" type="submit" ays_text="You will lose any unsaved changes... Do you want to continue?" >Do something dangerous</button>
2. Attach handlers to ALL such buttons:
2. 将处理程序附加到所有此类按钮:
$('button[ays_text]').click(function (e, from) {
if (from == null) { // user clicked it!
var btn = $(this);
e.preventDefault();
if (confirm() == true) {
btn.trigger('click', ['your-app-name-here-or-anything-that-is-not-null']);
}
}
// otherwise - do nothing, ie continue default
});
That's it.
就是这样。
回答by Udayantha Udy Warnasuriya
$('#myform').on('submit',function(event){
// block form submit event
event.preventDefault();
// Do some stuff here
...
// Continue the form submit
event.currentTarget.submit();
});
回答by Akash
With jQueryand a small variation of @Joepreludian's answer above:
jQuery上面@Joepreludian 的回答有一个小的变化:
Important points to keep in mind:
要记住的要点:
.one(...)instead on.on(...) or .submit(...)namedfunction instead ofanonymous functionsince we will be referring it within thecallback.
.one(...)而是在.on(...) or .submit(...)named函数而不是anonymous function因为我们将在callback.
$('form#my-form').one('submit', function myFormSubmitCallback(evt) {
evt.stopPropagation();
evt.preventDefault();
var $this = $(this);
if (allIsWell) {
$this.submit(); // submit the form and it will not re-enter the callback because we have worked with .one(...)
} else {
$this.one('submit', myFormSubmitCallback); // lets get into the callback 'one' more time...
}
});
You can change the value of allIsWellvariable in the below snippet to trueor falseto test the functionality:
您可以allIsWell将以下代码段中的变量值更改为true或false测试功能:
$('form#my-form').one('submit', function myFormSubmitCallback(evt){
evt.stopPropagation();
evt.preventDefault();
var $this = $(this);
var allIsWell = $('#allIsWell').get(0).checked;
if(allIsWell) {
$this.submit();
} else {
$this.one('submit', myFormSubmitCallback);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/" id="my-form">
<input name="./fname" value="John" />
<input name="./lname" value="Smith" />
<input type="submit" value="Lets Do This!" />
<br>
<label>
<input type="checkbox" value="true" id="allIsWell" />
All Is Well
</label>
</form>
Good Luck...
祝你好运...
回答by alairock
In a pure Javascript way, you can submit the form after preventing default.
以纯Javascript的方式,您可以在防止默认后提交表单。
This is because HTMLFormElement.submit()never callsthe onSubmit(). So we're relying on that specification oddity to submit the form as if it doesn't have a custom onsubmit handler here.
这是因为HTMLFormElement.submit()从来没有要求的onSubmit()。因此,我们依靠该规范的奇怪之处来提交表单,就好像它在这里没有自定义的 onsubmit 处理程序一样。
var submitHandler = (event) => {
event.preventDefault()
console.log('You should only see this once')
document.getElementById('formId').submit()
}
See this fiddlefor a synchronous request.
有关同步请求,请参阅此小提琴。
Waiting for an async request to finish up is just as easy:
等待异步请求完成同样简单:
var submitHandler = (event) => {
event.preventDefault()
console.log('before')
setTimeout(function() {
console.log('done')
document.getElementById('formId').submit()
}, 1400);
console.log('after')
}
You can check out my fiddle for an exampleof an asynchronous request.
您可以查看我的小提琴以获取异步请求的示例。
And if you are down with promises:
如果你对承诺感到失望:
var submitHandler = (event) => {
event.preventDefault()
console.log('Before')
new Promise((res, rej) => {
setTimeout(function() {
console.log('done')
res()
}, 1400);
}).then(() => {
document.getElementById('bob').submit()
})
console.log('After')
}
And here's thatrequest.
这是那个请求。
回答by Dennis Heiden
"Validation injection without submit looping":
“没有提交循环的验证注入”:
I just want to check reCaptcha and some other stuff before HTML5 validation, so I did something like that (the validation function returns true or false):
我只想在 HTML5 验证之前检查 reCaptcha 和其他一些东西,所以我做了类似的事情(验证函数返回 true 或 false):
$(document).ready(function(){
var application_form = $('form#application-form');
application_form.on('submit',function(e){
if(application_form_extra_validation()===true){
return true;
}
e.preventDefault();
});
});
回答by Royi Namir
You can use e.preventDefault()which will stop the current operation.
您可以使用e.preventDefault()which 将停止当前操作。
than you can do$("#form").submit();
比你能做的$("#form").submit();
$('#form').submit(function (e)
{
return !!e.submit;
});
if(blabla...)
{...
}
else
{
$('#form').submit(
{
submit: true
});
}

