单击和双击同一元素,不起作用; Javascript

Single click and Double click on the same element, not working; Javascript

我正在尝试添加点击按钮时触发的点击功能。我也在尝试弄清楚如何在触发不同事件的同一元素上添加双击功能。

var click = false;
onEvent("image2", "click", function(event) {
  click = true;
});
if (click === true) {
  setTimeout(function() {
    onEvent("image2", "click", function(event) {
      setScreen("safeScreen");
      console.log("double click");
    });
  }, 200);
} else {
  onEvent("image2", "dblclick", function(event) {
    setScreen("safeScreen");
    console.log("click");
  });
}

这段代码是完全错误的,但我不知道去哪里了start/correct。我究竟做错了什么?我希望当用户双击时不会触发单击。

更新:

尝试像这样将函数 clicks() 传递给您的事件侦听器:

onEvent("image2", "click", clicks);

函数 clicks() 将检查是否有基于 setTimeout 函数的单击或双击。您可以通过 timeout 变量调整 setTimeout,当然您需要在 clicks() 函数之外声明的 clickCount 变量。


纯js方法

尝试添加两个事件侦听器。更少的代码,更干净。检查这个工作示例。

var selector = document.getElementById('codeorg');
selector.addEventListener('click', clicks);


// Global Scope variable we need this
var clickCount = 0;
// Our Timeout, modify it if you need
var timeout = 500;
// Copy this function and it should work
function clicks() {
  // We modify clickCount variable here to check how many clicks there was
  
      clickCount++;
      if (clickCount == 1) {
        setTimeout(function(){
          if(clickCount == 1) {
            console.log('singleClick');
            // Single click code, or invoke a function 
          } else {
            console.log('double click');
            // Double click code, or invoke a function 
          }
          clickCount = 0;
        }, timeout || 300);
      }
}



// Not important for your needs - pure JS stuff
var button = document.getElementById('button');

button.addEventListener('click', singleClick);
button.addEventListener('dblclick', doubleClick);

function singleClick() {
  //console.log('single click');
}

function doubleClick() {
  console.log('double click');
}
#codeorg {
  margin-bottom: 100px;
}
<h2>Double Click</h2>

<button id="button">Click me</button>


<hr><hr>


<h2>Double click or Single Click</h2>

<button id="codeorg">Click me</button>