Double click ambiguity in Jquery?

二次信任 提交于 2019-12-06 06:33:10

问题


I am trying to set some text in window for single and double click in jquery.

But I am facing the ambiguity for double click.

When trying to do double click , first single click function works and then double click works.

Similar question is here check here and it was very old. Also it has some problem.

Any new answer using the latest jquery version.

Check the live demo here of my problem live demo

This my code ,

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

<a id="press" href="http://jquery.com">Click here</a>
<div id="log"></div>

<script>

$("#press").click(function(event) {
  event.preventDefault();
  $("#log").text("I am single click !");
return false;
});

$("#press").dblclick(function(event) {
      event.preventDefault();
      $('#log').text("I am double  click !");
      return false;
    });
</script>

</body>
</html>

Hope our stack users will help me.


回答1:


The way around the problem is to use a timeout for the click event to give the user time to doubleclick.
If the user clicks twice within a certain timeframe, it's a doubleclick, if the user only clicks once, it's a normal click:

$('#press').click(function (event) {
    event.preventDefault();

    if ( $(this).data('dblclicked') ) {
        $('#log').text('No google today!');
        clearTimeout( $(this).data('clicked') );
        $(this).data('dblclicked', false);
    }else{
        var self = this;
        $(this).data('dblclicked', true).data('clicked', setTimeout(function() {
            $('#log').text('google !');
            $(self).data('dblclicked', false);
        },300));
    }
});

FIDDLE




回答2:


I got the closest solution by ,

<a id="press" href="javascript:void(0)" onclick="singleClick(event)"
    ondblclick="doubleClick(event)">Click here</a>

<div id="log"></div>

My JavaScript will be ,

var timer;
var status = 1;

function singleClick(event) {

    event.preventDefault();
    status = 1;
    timer = setTimeout(function() {
        if (status == 1) {
            alert("I am single click !");
            document.getElementById("log").innerHTML ='I  am single click !';
        }
    }, 500);

}

function doubleClick(event) {

    event.preventDefault();
    clearTimeout(timer);
    status = 0;
    alert("I am double click !");
    document.getElementById("log").innerHTML = 'I  am a double  click!';
}


来源:https://stackoverflow.com/questions/17921556/double-click-ambiguity-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!