如何区分单击事件和双击事件? [英] how to differentiate single click event and double click event?
本文介绍了如何区分单击事件和双击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在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/
这篇关于如何区分单击事件和双击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文