jQuery鼠标双击时误触发click事件解决方法

当页面按钮同时绑定了dblclick和click两个事件时,双击会发现触发了一次dblclick事件和两次click事件:

<input name="btn1" id="btn1" type="button" value="随便点">
<script type="text/javascript">
$(document).ready(function(){
    $("#btn1").on("click", function(){console.log("click")});
    $("#btn1").on("dblclick", function(){console.log("dblclick")});
});
</script>



也就是说,误触发了两次click事件,怎么避免呢?将代码稍做修改:

<input name="btn1" id="btn1" type="button" value="随便点">
<script type="text/javascript">
$(document).ready(function(){
    let timer = null;

    $("#btn1").on("click", function(){
        if(timer){clearTimeout(timer)}
        timer = setTimeout(function(){console.log("click")}, 300);
    });

    $("#btn1").on("dblclick", function(){
        if(timer){clearTimeout(timer)}
        console.log("dblclick");
    });
});
</script>



OK,问题解决!

评论: 0 | 引用: 0 | 查看次数: 233
发表评论
登录后再发表评论!