问题描述
我只是想知道为什么单击
事件发生时,我 dbclick
一个元素?
I'm just wondering why click
event happening when I dbclick
an element?
我有这个代码:( )
I have this code:(JSBIN)
HTML
<p id="hello">Hello World</p>
JavaScript
document.getElementById('hello').addEventListener('click', function(e){
e.preventDefault();
this.style.background = 'red';
}, false);
document.getElementById('hello').addEventListener('dbclick', function(){
this.style.background = 'yellow';
}, false);
它应该为点击和双击做不同的事情,但是当您双击 p
它抓住提前点击
事件,忽略双击。
It should do different things for click and double click, but it seems when you double click on the p
it catch click
event in advance and ignore double click.
我尝试了 preventDefault
点击
事件。
如何只听 dbclick
?
我的代码中有打字错误。 dbclick
是错误的。这是 dblclick
。无论如何,问题仍然存在。当用户双击点击
事件时。
I had a typo in my code. dbclick
is wrong. It's dblclick
. Anyway the problem still exist. When user double clicks the click
event happens.
这是更新的代码,证明它:( )
This is updated code that prove it:(JSBin)
document.getElementById('hello').addEventListener('click', function(e){
e.preventDefault();
this.style.background = 'red';
this.innerText = "Hello World clicked";
}, false);
document.getElementById('hello').addEventListener('dblclick', function(){
this.style.background = 'green';
}, false);
推荐答案
dblclick
不是神奇的:虽然第二个快速点击
触发 dblclick
事件,第一个点击
已经触发了自己的事件处理程序。
dblclick
is not magical: though the second rapid click
fires the dblclick
event, the first click
has already triggered its own event handler.
你应该几乎从不设置点击
和一个 dblclick
事件在DOM元素上;当你这样做的时候,你需要花时间的手段和计时器来减轻这个问题。
You should pretty much never set both a click
and a dblclick
event on a DOM element; when you do, you'll need fancy tricks with timers to mitigate the issue.
在这个具体情况下,你还需要修正你的错字( s / dbclick / dblclick /
)以使事件触发。
In this specific scenario, you'll also need to fix your typo (s/dbclick/dblclick/
) to get the event to fire at all.
这篇关于听双击不点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!