点击事件后,如何点燃Javascript模糊事件会导致模糊? [英] How should I fire Javascript blur event after click event that causes the blur?

查看:106
本文介绍了点击事件后,如何点燃Javascript模糊事件会导致模糊?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遇到这个问题了几次,我对以前使用的解决方案感到不满意。

I have run into this problem a few times and I'm not happy with the solutions I've used before.

我有一个模糊的输入框事件验证它的内容和一个按钮,将填写输入框点击。问题是点击按钮可以触发输入模糊事件,然后按钮点击事件,因此按钮插入的内容不是有效的。

I have an input box with a blur event that validates the content of it and a button which will fill the input box on click. The problem is clicking the button fires the input blur event and then the button click event so content inserted by the button is not what is validated.

请参阅 http://jsfiddle.net/jakecr/dL3K3/

我知道这是正确的行为,但我不能想到一个干净的方式来解决问题。

I know this is the correct behavior but I can't think of a clean way to get around the problem.

推荐答案

一个类似的问题在工作。最后我们想到的是
是mousedown事件会在模糊事件
之前触发,允许您在验证之前设置内容,甚至使用标志完全取消验证
进程。

We had a similar problem at work. what we figured out in the end was that the mousedown event will fire before the blur event allowing you to set the content before the validation or even cancel the validation process completely using a flag.

检查我使用你的例子的这个小提琴 -
http://jsfiddle.net/dL3K3/31/

check this fiddle I made using your example- http://jsfiddle.net/dL3K3/31/

$(function(){
    var flag = true;
    $('input').blur(function(){
        if(!$(this).val() && flag){
            alert("Grrr, It's empty");
        }
    });

    $('button').mousedown(function(){
        flag = false;
    });    
    $('button').mouseup(function(){
        flag = true;
        $('input').val('content').focus();
    });

});

-Edit-

As @mclin建议使用mousedown事件和preventDefault将防止模糊行为。
您可以保留原始点击事件 -

As @mclin Suggested, using the mousedown event and preventDefault will prevent blur behavior. And you can just leave the original click event intact -

http://jsfiddle.net/dL3K3/364/

$(function(){
    $('input').blur(function(){
        if(!$(this).val()){
            alert("Grrr, It's empty");
        }
    });

    $('button').mousedown(function(e){
        e.preventDefault();
    });    
    $('button').click(function(){
        $('input').val('content');
    });

});

这个解决方案可能会更清洁,更适合大多数情况,只需要注意,如果你使用它,将会阻止任何其他重点目前的元素的默认和模糊,但大多数情况下不应该是一个问题。

This solution might be a bit cleaner and better for most cases just note that if you use it you'll preventDefault and blur of any other element the focus is currently on but for most use cases that shouldn't be an issue.

这篇关于点击事件后,如何点燃Javascript模糊事件会导致模糊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆