【解决方案】如何解决输入框失焦事件与按钮点击事件冲突的问题

直接上代码(demo可直接拷贝运行):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <style type="text/css">
        .father{
            width: 500px;
            height: 300px;
            background: green;
            padding-top: 20px;
        }
        .father input {
            width: 120px;
            height: 28px;
            border: 1px solid blue;
        }
        .father button{
            width: 60px;
            height: 28px;
            margin-left: 10px;
        }
    </style>
    <script>
        function btn() {
            alert("you click it");
        }
    </script>
</head>
<body>
<div class="father" id="father" tabindex="1">
    <input id="testInput" placeholder="请输入您的信息"><button id="testBtn" onclick="btn()">提交</button>
</div>
</body>
<script>
    //  鼠标按下事件
    $("#testBtn").mousedown(function(){
        alert("my button mousedown");
    });
    
    //  输入框失焦事件
    $("#testInput").blur(function(){
        alert("now blur  ~~~");
    });

    //  输入框失焦事件 延迟触发
//    $("#testInput").blur(function(){
//        setTimeout(function(){
//            alert("now blur  ~~~");
//        }, 300)
//    });
</script>
</html>

问题描述:

给一个输入框设置失焦事件之后,失焦事件总是优先其它事件先触发,导致输入完成之后点击提交按钮无效。


解决方案:

方法1、通过给失焦事件设置延迟触发。

方法2、将按钮的点击(click)事件改为按下(mousedown)事件。


参考链接:快速解决js开发下拉框中blur与click冲突


posted @ 2017-08-20 15:39  Mr.Kay  阅读(1538)  评论(0编辑  收藏  举报