How can jQuery be used to handle timer in click, d

2020-02-04 20:59发布

I am using the jQueryFileTree at http://abeautifulsite.net/notebook/58 and I want to distinguish between the dblclick and click events as a click is always triggered by a dblclick.

Googling about led to be a technique in which click is handled by a timer which kicks in when a dblclick does not cancel it.

Is there some way this can be used with jQuery and the jQuery example in an elegant manner?

3条回答
疯言疯语
2楼-- · 2020-02-04 21:33

You can use setTimeout() and clearTimeout() to realize the timer functionality:

var timeout;
var delay = 500;  // Delay in milliseconds

$("...")
    .click(function() {
        timeout = setTimeout(function() {
            // This inner function is called after the delay
            // to handle the 'click-only' event.
            alert('Click');
            timeout = null;
        }, delay)
    }
    .dblclick(function() {
        if (timeout) {
            // Clear the timeout since this is a double-click and we don't want
            // the 'click-only' code to run.
            clearTimeout(timeout);
            timeout = null;
        }
        // Double-click handling code goes here.
        alert('Double-click');
    }
;
查看更多
欢心
3楼-- · 2020-02-04 21:43

Look at the following code

$("#clickMe").click(function (e) {
    var $this = $(this);
    if ($this.hasClass('clicked')){
        alert("Double click");
        //here is your code for double click
        return;
    }else{
         $this.addClass('clicked');
        //your code for single click
         setTimeout(function() { 
                 $this.removeClass('clicked'); },500);
    }//end of else
});

Demo goes here http://jsfiddle.net/cB484/

查看更多
够拽才男人
4楼-- · 2020-02-04 21:46

jQuery Sparkle provides a clean elegant solution for this, by implementing a singleclick custom event. By doing this, you can use it just like any other event, so:

$('#el').singleclick(function(){});
// or event
$('#el').bind('singleclick', function(){});

It also provides custom events for the last and first clicks of a series of clicks. And the lastclick custom event actually passes the amount of clicks back! So you could do this!

$('#el').lastclick(function(event,clicks){
    if ( clicks === 3 ) alert('Tripple Click!');
});

You can find the appropriate demo showcasing what I've just said right here and the source code for defining the custom event right here. It's open source under the AGPL licence, so you can feel free to grab what you need out of it worry free! :-) It's also actively developed on a day to day basis so you will never be short on support.

But most importantly it is a DRY Plugin/Effect Framework to allow you to develop plugins and extensions much more easily. So I hope this helps to achieve that goal!

查看更多
登录 后发表回答