从时必然要输入焦点,并单击两次射击prevent功能 [英] Prevent function from firing twice when bound to input on focus and click

查看:111
本文介绍了从时必然要输入焦点,并单击两次射击prevent功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到一个触发事件,两个点击焦点,但是我只希望它火一次。当我点击输入里面,它触发两次(点击和聚焦)。我怎样才能prevent呢?

  $('输入')。在('专注点击',功能(){
    的console.log('解雇');
});


解决方案

您可以使用 。一是 代替。这将只允许事件触发一次,但也将删除绑定一旦已烧制

  $('输入')。一(焦点点击',功能(){
    的console.log('解雇');
});

如果你需要保持绑定你将不得不按住鼠标按钮的状态,并触发当前目标的轨道鼠标按下

  VAR MOUSEDOWN,currentTarget当前;
$('输入')。在({
    鼠标按下鼠标松开:功能(E){
        MOUSEDOWN = e.type ===鼠标按下
        currentTarget当前= e.target;
    },
    FOCUS单击:功能(E){
        如果(MOUSEDOWN&安培;&安培; currentTarget当前=== e.target)回报;
        的console.log('解雇');
    }
});

请参阅上的jsfiddle 测试用例。

I'm attempting to get an event to fire on both click and focus, however I only want it to fire once. When I click inside an input, it fires twice (clicking and focusing). How can I prevent this?

$('input').on('focus click', function(){
    console.log('fired');
});

You can use .one instead. That will only allow the event to fire once, but will also remove the bind once it has been fired:

$('input').one('focus click', function(){
    console.log('fired');
});

If you need to keep the bind you will have to keep track of the state of the mouse button and the current target that triggered the mousedown:

var mouseDown, currentTarget;
$('input').on({
    "mousedown mouseup": function (e) {
        mouseDown = e.type === "mousedown";
        currentTarget = e.target;
    },
    "focus click": function (e) {
        if (mouseDown && currentTarget === e.target) return;
        console.log('fired');
    }
});

See test case on jsFiddle.

这篇关于从时必然要输入焦点,并单击两次射击prevent功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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