jQuery中的焦点方法没有;不起作用

The focus method in jQuery doesn't work

本文关键字:不起作用 方法 焦点 jQuery      更新时间:2023-09-26

以下代码用于检查模糊字段中是否输入了4个数字。如果没有,则删除字段值,并聚焦字段。删除操作很好,但对focus()的调用不起作用。

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

为什么对focus()的调用没有聚焦字段?

由于blur事件在实际失焦之前触发,因此不能立即使用.focus()。您必须将它向下推到堆栈中,以便它在input失去焦点后执行。将.focus()放入计时器(无需延迟):

$('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/

演示http://jsfiddle.net/dsaSX/3/

尝试使用this.value而不是$(this).attr(...)

休息希望这有助于事业,:)

如果您使用的是Jquery 1.7及以上版本,那么我已经使用了.on事件。

阅读以下内容:What';jQuery.val()和.attr(';value';)之间的区别是什么?

阅读此处http://forum.jquery.com/topic/jquery-focus-after-blur

以及另一个已知论坛带有SetTimeOut的解决方案http://forum.jquery.com/topic/focus-inside-a-blur-handler见下方的帖子

代码

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

使用focusout 而不是模糊

http://jsfiddle.net/fedmich/aKY9f/


提示:

缩进你的代码

值使用$.val('')而不是attr

在使用IF()时,请使用制动器{}

写得更干净,尽可能简单,这样你以后就不会感到困惑。

快乐编码:)

小细节,

大多数时候我读到这样的问题。这通常是因为事件不正确。在要求系统将焦点设置为某个内容之前,请确保您的页面已处理完毕。

这里有一个例子,事件pageshow比pagebeforeshow更好

不能这样工作

/**
 *** a hook to handle list drawing. DOES NOT WORK**
 */
$(document).delegate('#dropdownPopupWindow', "pagebeforeshow", function() {
    console.log(UIPopup.TAG+"pagebeforeshow on popup dropdownPopupWindow is setting focus on field field_dropdown_label");
    $('#field_dropdown_label').focus();
});

这样工作

/**
 *** a hook to handle list drawing.**
 */
$(document).delegate('#dropdownPopupWindow', "pageshow", function() {
    console.log(UIPopup.TAG+"pageshow on popup dropdownPopupWindow is setting focus on field field_dropdown_label");
    $('#field_dropdown_label').focus();
});

如果您使用Bootstrap模式,这将不起作用:

$('#modalID').modal('show');
$('#modalID #fieldID').focus();

因为模态需要一点时间才能绘制出来并可用于聚焦。。。我发现400毫秒的超时足够快,用户不会受到影响,而且足够慢,它总是专注于元素。

$('#modalID').modal('show');
setTimeout(function(){  $('#modalID #fieldID').focus(); }, 400);

事实上,使用可执行注释也无妨:

function wait_for_modal_to_be_drawn_then( fn )
{
  setTimeout( fn, 400 );
}
$('#modalID').modal('show');
wait_for_modal_to_draw_then( 
     function(){  $('#modalID #fieldID').focus(); } 
);