How to disable double clicks or timeout clicks with jQuery?

后端 未结 3 1416
情书的邮戳
情书的邮戳 2021-01-16 06:30

I have an anchor which is using jQuery .click event to start a few functions.

jQuery(document).ready(function(){  
    jQuery(\'a.slide_circ\').click(functio         


        
相关标签:
3条回答
  • 2021-01-16 06:47

    Use the .data method to assign the state to the element. Then, use setTimeout to reset the state:

    jQuery(document).ready(function() {
        jQuery('a.slide_circ').click(function() { 
            var $this = jQuery(this);
            if ($this.data('activated')) return false;  // Pending, return
    
            $this.data('activated', true);
            setTimeout(function() {
                $this.data('activated', false)
            }, 500); // Freeze for 500ms
    
            do_all_functions();
            return false; 
        });
    });
    
    0 讨论(0)
  • 2021-01-16 06:50

    A few ways to do it, but one way is:

    jQuery(document).ready(function(){ 
        var do_all_functions_running = false; 
        jQuery('a.slide_circ').click(function(){
            if (!do_all_functions_running) { 
                do_all_functions_running = true;
                do_all_functions();
                do_all_functions_running = false;
            }
            return false;   
        });  
    });
    

    Not perfect, but it'll work.

    0 讨论(0)
  • 2021-01-16 06:53

    You can check the last date of the run, and cancel if it was less than half a second ago:

    jQuery(document).ready(function() {
        jQuery('a.slide_circ').each(function() {
            var lastRun = null;
    
            $(this).click(function() {
                if(lastRun && new Date() - lastRun < 500) {
                    // Less than 500ms; ignore.
                    return false;
                }
    
                // Set the last run:
                lastRun = new Date().getTime();
    
                // Continue:
                do_all_functions();
                return false; 
            });
        });
    });
    

    It has the advantage of being a little more efficient.

    0 讨论(0)
提交回复
热议问题