如何检查输入字段是否在焦点上? [英] How do I check if input field is in focus or not?

查看:97
本文介绍了如何检查输入字段是否在焦点上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在输入字段处于焦点(即光标位于其中)时才发送Ajax请求.这是我的代码:

I want to send an Ajax request only when my input field is in focus (i.e., cursor is inside it. Here's my code:

function anewFunc() {
    $(document).ready(function(){
        var chatattr = $(".chatwindow").css("visibility");
        var chattitle = $("#hideid").text();
        if (chatattr == "visible") {
            if (MY INPUT FIELD HAS FOCUS) {
                $.ajax({
                    url: 'seen1.php',
                    type: 'post',
                    data: "ctitle="+chattitle,
                    success: function(result9) {},
                    error: function() {}
                });
            }
        } else {
            $.post("seendefault.php");
        }
    });
}

$(document).ready(function(){
    var zzz = setInterval(anewFunc, 2000);
});

现在我不知道每次输入是否具有焦点时如何检查.有任何jQuery解决方案吗?

Now I don't know how to check every time the input has focus or not. Is there any jQuery solution for it?

一些答案建议我:专注.所以我尝试了这个:

A few answers has suggested me :focus. So I tried this for trial:

$(document).ready(function(){
                           if($("#msgtypeid").is(":focus")){
                               alert("Hello");
                           }
                           });

HTML:

<form id="chatform" name="form4" method="post" required enctype="multipart/form-data">
          <input id="msgtypeid" type="text" name="cmessage" autocomplete="off" autofocus/>
        </form>

但是它不起作用.有什么问题吗?

But it's not working. Is there something wrong?

推荐答案

我认为您需要这种类型的检查:

I think you need this type of a checking:

var hasFocus = $('#idOfTheInputElement').is(':focus');
if(hasFocus){
    //logic here
}

这篇关于如何检查输入字段是否在焦点上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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