使用用于撰写电子邮件的表单,我们使用计时器自动保存更改。这很好用。但是在提交表单时似乎存在竞争,尤其是IE11。在提交时,我们希望在提交发生之前关闭自动保存。我们在生产中有实例,我们可以同时调用服务器来保存草稿以及提交表单。
var timeoutId;
var deleted = false;
// setup a call to onFormChange when a change happens
$('form input, form textarea').on('input propertychange change', function() {
onFormChange();
});
function onFormChange() {
// call saveDraft 1 second after changes happen
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {saveDraft();}, 1000);
}
// saveDraft saves the current form state in the draft.
function saveDraft() {
if (deleted == true) {
// don't save because we're done
return;
}
var fromval = $("#from").val();
var subject = $("#subject").val();
var body = $("#body").val();
//
// upload is done here using $.post()
//
}
$('form').submit(function(e){
// stop saving drafts when we do a submit
deleted = true;
if( $(this).hasClass('form-submitted') ){
e.preventDefault();
return;
}
$(this).addClass('form-submitted');
});
答案 0 :(得分:2)
提交表单时停止计时器。
$('form').submit(function(e){
// stop saving drafts when we do a submit
deleted = true;
if( $(this).hasClass('form-submitted') ){
e.preventDefault();
return;
}
$(this).addClass('form-submitted');
clearTimeout(timeoutId);
});