jQuery中的焦点方法不起作用 [英] The focus method in jQuery doesn't work

查看:452
本文介绍了jQuery中的焦点方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码旨在检查模糊字段中是否输入了4个数字。如果不是,则删除字段值,并且该字段被聚焦。删除工作正常,但对focus()的调用不起作用。

The following code is intended to check if 4 numbers are entered in the blurred field. If not, the field value is deleted, and the field is focused. The deletion works fine, but the the call to focus() does not work.

$('input.dateValue').live('blur',function(event){
  if (!(/(\d){4}$/.test($(this).attr('value')))) $(this).attr('value','').focus();
});

为什么对焦点()的调用不关注该字段?

Why does the call to focus() not focus the field?

推荐答案

由于 blur 事件在实际失去焦点之前触发,因此无法使用 .focus()马上。你必须将它压低堆栈,以便在输入失去焦点后执行。将 .focus()放入计时器(无需延迟):

Since the blur event fires before the actual loss of focus, you cannot use .focus() right away. You have to push it down the stack, so that it executes after the input has lost focus. Put your .focus() in a timer (no delay necessary):

$('input.dateValue').on('blur', function(event)
{
    if ( ! /(\d){4}$/.test(this.value) )
    {
        var $this = $(this).val('');

        setTimeout(function (){
            $this.focus();
        }, 0);
    };
});​

以下是小提琴: http://jsfiddle.net/TdfFs/

更新:为了证明此在Chrome中运行,我又做了一个小提琴: http://jsfiddle.net/TdfFs/1/

Update: to demonstrate that this does work in Chrome, I made another fiddle: http://jsfiddle.net/TdfFs/1/

这篇关于jQuery中的焦点方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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