How to prevent a double-click using jQuery?

前端 未结 15 793
孤街浪徒
孤街浪徒 2020-11-30 23:42

I have a button as such:


Within jQuery I am using the following, but it still

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 00:38

    I had a similar issue, but disabling the button didn't fully did the trick. There were some other actions that took place when the button was clicked and, sometimes, button wasn't disabled soon enough and when the user double-clicked, 2 events where fired.
    I took Pangui's timeout idea, and combined both techniques, disabling the button and includeding a timeout, just in case. And I created a simple jQuery plugin:

    var SINGLECLICK_CLICKED = 'singleClickClicked';
    $.fn.singleClick = function () {
        var fncHandler; 
        var eventData;
        var fncSingleClick = function (ev) {
            var $this = $(this);
            if (($this.data(SINGLECLICK_CLICKED)) || ($this.prop('disabled'))) {
                ev.preventDefault();
                ev.stopPropagation();
            }
            else {
                $this.data(SINGLECLICK_CLICKED, true);
                window.setTimeout(function () {
                    $this.removeData(SINGLECLICK_CLICKED);
                }, 1500);
                if ($.isFunction(fncHandler)) {
                    fncHandler.apply(this, arguments);
                }
            }
        }
    
        switch (arguments.length) {
            case 0:
                return this.click();
            case 1:
                fncHandler = arguments[0];
                this.click(fncSingleClick);
                break;
            case 2: 
                eventData = arguments[0];
                fncHandler = arguments[1];
                this.click(eventData, fncSingleClick);
                break;
        }
        return this;
    }
    

    And then use it like this:

    $("#button1").singleClick(function () {
       $(this).prop('disabled', true);
       //...
       $(this).prop('disabled', false);
    })
    

提交回复
热议问题