簡體   English   中英

jQuery中的焦點方法不起作用

[英]The focus method in jQuery doesn't work

以下代碼用於檢查模糊字段中是否輸入了4個數字。 如果不是,則刪除字段值,並且該字段被聚焦。 刪除工作正常,但對focus()的調用不起作用。

$('input.dateValue').live('blur',function(event){
  if (!(/(\d){4}$/.test($(this).attr('value')))) $(this).attr('value','').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事件。

閱讀: 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();
    };
});​

而不是模糊使用焦點

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


提示:

縮進你的代碼

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

在使用IF()時,請使用brakets {}

寫得更干凈,盡可能簡單,這樣你以后就不會感到困惑。

快樂編碼:)

小細節,

大多數時候我都會讀到這樣的問題。 這通常是因為事件不正確。 在要求系統將注意力集中在某些內容之前,請確保已處理您的頁面。

這里是一個示例,其中事件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();

因為繪制模態需要一些時間並且可用於聚焦...我發現400ms的超時足夠快,用戶不會受到影響並且足夠慢以至於它始終關注元素。

$('#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(); } 
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM