Jquery - 在使用两者时区分“click”和“focus”在同一输入上 [英] Jquery - Differentiate between 'click' and 'focus' on same input when using both

查看:183
本文介绍了Jquery - 在使用两者时区分“click”和“focus”在同一输入上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果输入被点击,如果输入进入焦点,我正试图在输入上触发事件。

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.

我遇到的问题是阻止事件在点击上触发两次,因为很明显,点击输入也会使其成为焦点。我在jfiddle上放了一个非常宽松的版本来向你展示我的意思,代码如下:

The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:

HTML:

<body>
    <input type="textbox" name="tb1" class="input1"></input>
    <label> box 1 </label>
    <input type="textbox" name="tb2" class="input2"></input>
    <label> box 2 </label>
</body>

JQuery

$(function () {
    $('.input2').click(function() {
        alert("click");
    });
    $('.input2').focus(function() {
        alert("focus");
    });
});

JSFiddle http://jsfiddle.net/XALSn/2/

你会看到当你选项卡输入2你得到一个警报,但如果你点击你得到两个。理想情况下,对于我的场景,它需要是一个警报而忽略另一个。它似乎也没有实际关注。

You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.

提前感谢任何建议。

推荐答案

如何在焦点上设置一个标志,以便我们可以触发焦点并忽略点击,但是也可以监听焦点元素的点击次数?合理?看一下演示jsFiddle - 如果你专注或点击未聚焦的 .index2 它会触发焦点事件并忽略点击。在聚焦时,点击它会触发点击。

How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.

我不知道为什么你会想要这个(我无法想象有人想要因为任何原因点击焦点元素(因为克拉在字段中已经激活)但是你去了:

I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:

$(function () {
    $('.input2').on("click focus blur", function(e) {
        e.stopPropagation();
        if(e.type=="click"){
            if($(this).data("justfocussed")){
                $(this).data("justfocussed",false);
            } else {
                //I have been clicked on whilst in focus
                console.log("click");
            }
        } else if(e.type=="focus"){
            //I have been focussed on (either by clicking on whilst blurred or by tabbing to)
            console.log("focus");
            $(this).data("justfocussed",true);
        } else {
            //I no longer have focus
            console.log("blur");
            $(this).data("justfocussed",false);
        }
    });
});

http://jsfiddle.net/XALSn/12/

这篇关于Jquery - 在使用两者时区分“click”和“focus”在同一输入上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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