为什么$(this).focus();在jQuery中聚焦时将不适用于同一元素 [英] Why $(this).focus(); will not work on the same element when focusout in jquery

查看:482
本文介绍了为什么$(this).focus();在jQuery中聚焦时将不适用于同一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初,当我迷迷糊糊地遇到一个问题是,我无法将焦点的光标固定在某个元素上时,我试图验证用户输入.这是代码

Initially i was trying to validate a user input when i stumbled with a problem is that i cant fix the cursor of the focus on an element when focusing out. this is the code

$("#ChapterCode").keydown(function(e){
    if(e.keyCode==9 || e.keyCode==13){
        if($(this).val()!=""){
            ChapterCode();
            get_fees();
            return true;
        }else{
            $(this).focus();
            return false;
        }
    }
});

这将起作用,因为return false将禁止单击TAB时更改焦点. 但是

this will work as return false will prohibit the focus from changing when clicking a TAB. however

$("#ChapterCode").focusout(function(e){
        if($(this).val()!=""){
            ChapterCode();
            get_fees();
            return true;
        }else{
            e.preventDefault();
            $(this).focus();
            return false;
        }
    });

这与模糊帮助不一样吗?我添加了e.preventDefault();知道它不会以防万一.再次感谢您的帮助. 请不要告诉我创建错误消息或类似的内容,因为这简直就是不可能.

this wont work same as for blur any help ? i added e.preventDefault(); knowing that it wont work just in case. Help is really appreciated thanks again. Please dont tell me to create an error message or something like that coz its simply out of the question.

推荐答案

在这里看起来像不同的浏览器行为.

It looks like different browser behavior there.

Chrome中,它就像那样工作.您可以在blurfocusout内设置焦点.

In Chrome it works just like that. You can set the focus within the blur or focusout.

FireFox并非如此.您需要将其包装为setTimeout().

FireFox does not this. You need to wrap it into a setTimeout().

$("#ChapterCode").focusout(function(e){
    if($(this).val()!=""){
        ChapterCode();
        get_fees();
        return true;
    }else{
        var self = $(this);
        setTimeout(function(){
          self.focus();
        }, 1);            
        return false;
    }
});

这会将焦点移回#ChapterCode.您无法完全防止盒子失去焦点.您需要引入一个保存this引用的变量,可以通过setTimeout()的闭包进行访问.

This will setback the focus to #ChapterCode. You cannot completly prevent the box from losing the focus. You need to introduce a variable that holds the this reference, which can be accessed via closure from setTimeout().

示例: http://www.jsfiddle.net/hGjwZ/1/

这篇关于为什么$(this).focus();在jQuery中聚焦时将不适用于同一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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