js general anti-duplicate submission method

Introduction:

        Sometimes browser users submit with faster hands, or the network freezes, and it is easy to submit multiple times

Solution principle:

        When the user clicks submit, the button is automatically disabled for 3 seconds, and the disable is automatically undone after 3 seconds

Effect:

Core code:

/**
 *  通用防止重复提交方法
 * @param buttonId
 */
function disableButton(buttonId) {
	debugger;
	var button = document.getElementById(buttonId);
	if (button) {
		button.disabled = true; // 禁用按钮
		setTimeout(function() {
			button.disabled = false; // 3秒后启用按钮
		}, 3000);
	}
}

Full code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>禁用按钮测试,3秒后自动解禁</title>
	</head>
	<body>
		<div style="text-align: center;padding: 200px;">
			<input id="test" onclick="disableButton('test')" type="button" value="提交">
		</div>
	</body>
	<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
	<script>
		/**
		 *  通用防止重复提交方法
		 * @param buttonId
		 */
		function disableButton(buttonId) {
			debugger;
			var button = document.getElementById(buttonId);
			if (button) {
				button.disabled = true; // 禁用按钮
				setTimeout(function() {
					button.disabled = false; // 3秒后启用按钮
				}, 3000);
			}
		}
	</script>
</html>

Guess you like

Origin blog.csdn.net/qq_36521848/article/details/131221198