在导致模糊的单击事件之后,我应该如何触发 Javascript 模糊事件? [英] How should I fire Javascript blur event after click event that causes the blur?

查看:20
本文介绍了在导致模糊的单击事件之后,我应该如何触发 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 事件会在 blur 事件之前触发吗允许您在验证之前设置内容,甚至取消验证完全使用标志处理.

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();
    });

});

-编辑-

正如@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天全站免登陆