2 回答
TA贡献1878条经验 获得超4个赞
布尔变量怎么样?
// outer scope
let hasSubmitted = false;
//...
form.submit(function(e) {
if(hasSubmitted)return;
hasSubmitted = true;
//...
或者:
const submitButton = $("#submit-button")
form.submit(function(e) {
submitButton.disabled = true;
TA贡献1966条经验 获得超4个赞
您可以在发送表单后立即删除submit事件处理程序,因此不会再次发送表单。
根据您使用的 jQuery 版本,您可以使用
$form.submit(false);
或者:
$form.off('submit');
$form.on('submit', (e) => e.preventDefault());
另一种选择是禁用提交按钮和可选的输入字段:
const $form = $('#form');
const $message = $('#message');
const $submit = $('#submit');
$form.submit((e) => {
e.preventDefault();
// Option 1: Remove submit event handler:
$form.off('submit');
$form.on('submit', (e) => e.preventDefault());
// Option 2: Disable the submit button:
$submit.prop('disabled', true);
// Disable all input fields (optional):
$form.find('input, textarea').prop('disabled', true);
// Add feedback message:
$message.text('Sending message...');
// Simulate request:
setTimeout(() => {
// Update feedback message:
$message.text('The message was sent successfully!');
}, 2000)
});
body {
font-family: monospace;
font-size: 16px;
margin: 0;
}
#form {
width: 50vw;
margin: 0 auto;
}
input,
textarea,
button {
display: block;
width: 100%;
padding: 8px;
margin-top: 8px;
box-sizing: border-box;
border: 2px solid black;
background: transparent;
font-family: monospace;
font-size: 16px;
}
#message {
margin-top: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="text" placeholder="Subject" />
<textarea placeholder="Message"></textarea>
<div id="message"></div>
<button type="submit" id="submit">Send</button>
</form>
- 2 回答
- 0 关注
- 82 浏览
添加回答
举报