【问题标题】:jquery: how to disable dblclick events?jquery:如何禁用 dblclick 事件?
【发布时间】:2017-06-16 02:29:18
【问题描述】:

前提: 开发一个图形散点图(使用 flotchart.org)我有一个 js 函数,它动态创建一个显示图像(按钮)以实现用户操作点击按钮(下面的示例代码中的“向左平移”)

问题: 当用户快速单击按钮时,会触发(不希望的)双击事件。 当鼠标悬停在按钮上时,如何禁用双击(因此只允许单击事件)?换句话说:在下面的代码中使用 unbind 或 dblclick 有什么问题?

function addButtonPanLeft(x, top, offset) {
    $('<img id="buttonPanLeft" class="navigationbutton" src="../images/pan-left.png" style="left:' + x + 'px;top:' + top + 'px"' + ' title="Pan Left">').appendTo(placeholder).click(function(e) {
        e.preventDefault();
        panleft();
    });

    // disabilito double click sul bottone
    $('#buttonPanLeft').unbind('dblclick');
}


function addButtonPanRight(x, top, offset) {
    $('<img id="buttonPanRight" class="navigationbutton" src="../images/pan-right.png" style="left:' + x + 'px;top:' + top + 'px"' + ' title="Pan Right">').appendTo(placeholder).click(function(e) {
        e.preventDefault();
        panright();
    });

    // disabilito double click sul bottone  NON FUNZIONA ??????
    $('#buttonPanRight').dblclick(function(e) {
        e.preventDefault();
        panright();
        log({
            text: "double click",
            type: 'debug'
        });
    });
}

非常感谢 乔治

【问题讨论】:

    标签: javascript jquery click double-click


    【解决方案1】:

    编辑:正如@Accountant م 在 cmets 中提到的,unbind 现在已被弃用。请改用类似的off

    unbind 删除所有事件处理程序,它不会阻止事件被触发。您需要做的是附加一个停止事件传播的事件处理程序:

    $('#buttonPanLeft').unbind('dblclick');
    $('#buttonPanLeft').dblclick(function(e){
        e.stopPropagation();
        e.preventDefault();
        return false;
    });
    

    编辑:我可能误解了你的问题。如果您想阻止双击的第二次单击触发click 处理程序,您可以执行以下操作:

    function handler(e){
        e.preventDefault();
        panleft();
        $(this).unbind('click');
        setTimeout(function(){$('#buttonPanLeft').click(handler)}, 500)
    }
    $('#buttonPanLeft').click(handler);
    

    这可以防止在 500 毫秒后发生另一个点击事件。

    DEMO

    【讨论】:

    • 在我提交的示例中,那个处理程序不是e.preventDefault(); 吗?谢谢
    • @Solyaris 您将处理程序附加到click,而不是dblclick
    • 太棒了!终于用stopPropagation(); 解决了!非常感谢!
    • 从 jQuery 3.0 开始,.unbind() 已被弃用。自 jQuery 1.7 起,它被 .off() 方法所取代,因此已经不鼓励使用它。 .来源:https://api.jquery.com/unbind/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    相关资源
    最近更新 更多