单击双击干扰。怎么解决这个?

时间:2014-12-30 22:10:10

标签: javascript jquery settimeout double-click

我遇到一个问题,即我的单击事件会干扰我的双击事件,即使我双击,也会调用单击事件。

这是我在SO上找到的解决方案之前的代码:

grid.bind('change', function() {
    SearchPSelected();
});

$('#PGrid').delegate('tbody>tr', 'dblclick', function(e) {
    SearchPSelected();
    GotoNextView();
});

在我按照SO上的解决方案后,我的代码在这里:

grid = $('#PGrid').data('kendoGrid');

var DELAY = 700,
    clicks = 0,
    timer = null;

grid.on("click", function(e) {
        clicks++; //count clicks

        if (clicks === 1) {
            timer = setTimeout(function() {

                grid.bind('change', function() {
                    SearchPSelected();
                }); //perform single-click action    

                clicks = 0; //after action performed, reset counter
            }, DELAY);
        } else {
            clearTimeout(timer); //prevent single-click action

            $('#PGrid').delegate('tbody>tr', 'dblclick', function(e) {
                SearchPSelected();
                GotoNextView();
            }); //perform double-click action

            clicks = 0; //after action performed, reset counter
        }
    })
    .on("dblclick", function(e) {
        e.preventDefault(); //cancel system double-click event
    });

使用尝试的解决方案,没有任何东西被调用(从firebug检查),我不知道为什么?我对js(不是我选择的语言)还是比较新的,所以我可能会遗漏一些东西?

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。以下是修复方法。我不得不在上面的解决方案中删除click和dblclick方法的冗余。

        var DELAY = 700,
        clicks = 0,
        timer = null;

        $('#PGrid').delegate('tbody>tr','click', function (e) {
            clicks++; //count clicks

            if (clicks === 1) {
                timer = setTimeout(function () {

                        SearchPSelected();

                    clicks = 0; //after action performed, reset counter
                }, DELAY);
            } else {
                clearTimeout(timer); //prevent single-click action

                    SearchSelected();
                    GotoNextView();

                clicks = 0; //after action performed, reset counter
            }
        });