萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實作按鈕點擊後 N 秒禁用倒數恢復:防重複提交

表單提交按鈕點擊後立即禁用並顯示倒數秒數,N 秒後自動恢復,防止使用者重複提交。提供基本版與可複用外掛版兩種實作。

基本版實作


<input type="button" id="btn1" value="提交1" />
<input type="button" id="btn2" value="提交2" />

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function disableWithCountdown($btn, seconds) {
    seconds = seconds || 3;
    var originalText = $btn.val();
    $btn.prop('disabled', true);
    
    var timer = setInterval(function() {
        $btn.val(originalText + ' (' + seconds + 's)');
        seconds--;
        if (seconds < 0) {
            clearInterval(timer);
            $btn.prop('disabled', false).val(originalText);
        }
    }, 1000);
}

$('#btn1, #btn2').on('click', function() {
    var $this = $(this);
    if ($this.prop('disabled')) return;
    disableWithCountdown($this, 5);
    // 執行提交邏輯
    // $.post(...);
});
</script>

jQuery 外掛版 (可鏈式呼叫、支援多按鈕)


$.fn.disableCountdown = function(seconds, options) {
    var settings = $.extend({
        textTemplate: '{text} ({sec}s)', // {text} 原文字, {sec} 剩餘秒數
        onDisable: $.noop,
        onEnable: $.noop
    }, options);

    return this.each(function() {
        var $el = $(this);
        if ($el.prop('disabled')) return; // 已禁用跳過
        
        var originalText = $el.is('input,button') ? $el.val() : $el.text();
        var sec = seconds || 3;
        
        $el.prop('disabled', true);
        settings.onDisable.call($el[0]);
        
        var timer = setInterval(function() {
            if (sec < 0) {
                clearInterval(timer);
                $el.prop('disabled', false);
                $el.is('input,button') ? $el.val(originalText) : $el.text(originalText);
                settings.onEnable.call($el[0]);
                return;
            }
            var txt = settings.textTemplate.replace('{text}', originalText).replace('{sec}', sec);
            $el.is('input,button') ? $el.val(txt) : $el.text(txt);
            sec--;
        }, 1000);
        
        // 儲存 timer 供外部取消
        $el.data('disableCountdownTimer', timer);
    });
};

// 使用範例
$('#submitBtn').on('click', function() {
    $(this).disableCountdown(10, {
        textTemplate: '請等待 {sec} 秒',
        onDisable: function() { console.log('禁用'); },
        onEnable: function() { console.log('恢復'); }
    });
    // 提交 AJAX...
});

// 外部強制取消 (如 AJAX 完成提前恢復)
function enableButton($btn) {
    var timer = $btn.data('disableCountdownTimer');
    if (timer) {
        clearInterval(timer);
        $btn.prop('disabled', false);
        $btn.removeData('disableCountdownTimer');
    }
}

進階:AJAX 完成自動恢復


$.fn.submitWithLock = function(seconds) {
    return this.each(function() {
        var $form = $(this);
        $form.on('submit', function(e) {
            e.preventDefault();
            var $submitBtn = $form.find('button[type=submit], input[type=submit]').first();
            $submitBtn.disableCountdown(seconds || 30);
            
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method') || 'POST',
                data: $form.serialize(),
                success: function() { enableButton($submitBtn); /* 成功處理 */ },
                error: function() { enableButton($submitBtn); /* 錯誤提示 */ }
            });
        });
    });
};

// 使用
$('form').submitWithLock(10);

UX 建議

  • 倒數期間顯示 Loading 狀態 (Spinner) 而非單純禁用,降低使用者焦慮。
  • AJAX 完成 (成功/失敗) 立即恢復按鈕,不必等倒數結束。
  • 提供鍵盤無障礙:Enter 提交同樣觸發鎖定邏輯。
copyright © 萬盛學電腦網 all rights reserved