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.
<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.
将处理程序附加到所有这些按钮上:
$('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
});
$('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...
}
});
您可以在下面的代码片段中将 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>
$('#myform').on('submit',function(event){
// block form submit event
event.preventDefault();
// Do some stuff here
...
// Continue the form submit
event.currentTarget.submit();
});