如何区分单击事件和双击事件?

问题描述:

我在li中有一个ID为my_id的按钮。我使用此元素附加了两个jquery 事件

I have a single button in li with id "my_id". I attached two jquery events with this element

1.

$("#my_id").click(function() { 
    alert('single click');
});

2。

$("#my_id").dblclick(function() {
    alert('double click');
});

但每次它给我单击

您需要使用超时来检查第一次点击后是否还有其他点击。

You need to use a timeout to check if there is an another click after the first click.

这是诀窍

// Author:  Jacek Becela
// Source:  http://gist.github.com/399624
// License: MIT

jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
  return this.each(function(){
    var clicks = 0, self = this;
    jQuery(this).click(function(event){
      clicks++;
      if (clicks == 1) {
        setTimeout(function(){
          if(clicks == 1) {
            single_click_callback.call(self, event);
          } else {
            double_click_callback.call(self, event);
          }
          clicks = 0;
        }, timeout || 300);
      }
    });
  });
}

用法:

$("button").single_double_click(function () {
  alert("Try double-clicking me!")
}, function () {
  alert("Double click detected, I'm hiding")
  $(this).hide()
})



<button>Click Me!</button>

编辑:

如下所述,更喜欢使用原生 dblclick 事件: http ://www.quirksmode.org/dom/events/click.html

As stated below, prefer using the native dblclick event: http://www.quirksmode.org/dom/events/click.html

或jQuery提供的: http://api.jquery.com/dblclick/

Or the one provided by jQuery: http://api.jquery.com/dblclick/