避免使用者短時間內瘋狂點擊按鈕(如重複送出表單、刷單),採用「點擊即禁用 + 倒數計時 + 自動恢復」模式。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>按鈕防重複點擊</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="button" id="btn" value="點下我" />
<script>
var $btn = $('#btn');
var waitSeconds = 30; // 禁用秒數
var timerId;
$btn.on('click', function() {
var $this = $(this);
if ($this.prop('disabled')) return; // 已禁用則忽略
$this.prop('disabled', true);
var originalText = $this.val();
var remaining = waitSeconds;
timerId = setInterval(function() {
$this.val('點下我(' + remaining + ')');
remaining--;
if (remaining < 0) {
clearInterval(timerId);
$this.prop('disabled', false).val(originalText);
}
}, 1000);
// 這裡放入實際業務邏輯,如 AJAX 提交
// doSubmit();
});
</script>
</body>
</html>
prop('disabled', true):原生禁用,防止所有點擊事件(含鍵盤空白鍵觸發)。setInterval 每秒更新按鈕文字顯示倒數。clearInterval 清除計時器,恢復按鈕狀態與文字。disabled 屬性,雙重保險。$.fn.disableFor = function(seconds, options) {
var opts = $.extend({ text: '請等待({sec})' }, options);
return this.each(function() {
var $el = $(this);
if ($el.prop('disabled')) return;
$el.prop('disabled', true);
var orig = $el.is('input,button') ? $el.val() : $el.text();
var sec = seconds;
var timer = setInterval(function() {
var txt = opts.text.replace('{sec}', sec);
$el.is('input,button') ? $el.val(txt) : $el.text(txt);
if (--sec < 0) {
clearInterval(timer);
$el.prop('disabled', false);
$el.is('input,button') ? $el.val(orig) : $el.text(orig);
}
}, 1000);
});
};
// 使用方式
$('#submitBtn').on('click', function() {
$(this).disableFor(10);
// doAjaxSubmit();
});