修改
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 表单提交防重复:网络慢时禁用按钮并显示「提交中」。
|
||||
*/
|
||||
(function (global) {
|
||||
"use strict";
|
||||
|
||||
function submitButtons(form) {
|
||||
if (!form) return [];
|
||||
return Array.prototype.slice.call(
|
||||
form.querySelectorAll('button[type="submit"], input[type="submit"]')
|
||||
);
|
||||
}
|
||||
|
||||
function lockForm(form, label) {
|
||||
if (!form) return false;
|
||||
if (form.dataset.submitGuard === "locked") return false;
|
||||
form.dataset.submitGuard = "locked";
|
||||
form.classList.add("is-form-submitting");
|
||||
submitButtons(form).forEach(function (btn) {
|
||||
if (btn.dataset.submitGuardOrig === undefined) {
|
||||
btn.dataset.submitGuardOrig =
|
||||
btn.tagName === "BUTTON" ? btn.textContent : btn.value;
|
||||
}
|
||||
btn.disabled = true;
|
||||
if (label) {
|
||||
if (btn.tagName === "BUTTON") btn.textContent = label;
|
||||
else btn.value = label;
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function unlockForm(form) {
|
||||
if (!form) return;
|
||||
delete form.dataset.submitGuard;
|
||||
form.classList.remove("is-form-submitting");
|
||||
submitButtons(form).forEach(function (btn) {
|
||||
btn.disabled = false;
|
||||
var orig = btn.dataset.submitGuardOrig;
|
||||
if (orig !== undefined) {
|
||||
if (btn.tagName === "BUTTON") btn.textContent = orig;
|
||||
else btn.value = orig;
|
||||
delete btn.dataset.submitGuardOrig;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function isLocked(form) {
|
||||
return !!(form && form.dataset.submitGuard === "locked");
|
||||
}
|
||||
|
||||
/** 已通过前端校验,发起最终 POST(页面将跳转) */
|
||||
function nativeSubmitOnce(form, label) {
|
||||
if (!form) return;
|
||||
lockForm(form, label || "提交中…");
|
||||
form.submit();
|
||||
}
|
||||
|
||||
global.FormSubmitGuard = {
|
||||
lock: lockForm,
|
||||
unlock: unlockForm,
|
||||
isLocked: isLocked,
|
||||
nativeSubmitOnce: nativeSubmitOnce,
|
||||
};
|
||||
})(typeof window !== "undefined" ? window : this);
|
||||
Reference in New Issue
Block a user