2015-09-25 44 views
0

我的頁面有元素加載ajax,我需要使用輸入去下一個輸入,textarea或選擇。 某些輸入有格式化數字的功能,但上述解決方案只運行一次。jquery on ready keypressed

$(document).on('keypress',function(){ 
    var inputs = $('input, select, textarea').on("keypress", function(e) { 
    if (e.which == 13) { 
     if ($(this).attr('data-format')) { 
      formatNumber($(this)); 
     } 
     e.preventDefault(); 
     var nextInput = inputs.get(inputs.index(this) + 1); 
     if (nextInput) { 
      nextInput.focus(); 
     } 
    } 
}); 
}); 
+0

如果這些元素是你需要使用事件的AJAX請求的響應動態附加代表團。 –

+1

每次用戶按下某個鍵時,都會將鍵盤處理程序綁定到每個輸入,select和textarea。你爲什麼要做嵌套的處理程序綁定? –

回答

0

正如Rory和Jason所提到的,您可能正在尋找活動代表團。這將允許任何初始不存在的新輸入一旦出現就仍然響應按鍵事件。下面是關於這個問題的好文章:https://learn.jquery.com/events/event-delegation/和你的代碼應該是這個樣子:

UPDATE:

$(document).on('keypress', 'input, select, textarea', function(e){ 

    var inputs = $("input, select, textarea"); 

    if (e.which == 13) { 
    if($(this).attr('data-format')){ 
     formatNumber($(this)); 
    } 
    e.preventDefault(); 
    var nextInput = inputs.get(inputs.index(this) + 1); 
    if (nextInput) { 
     nextInput.focus(); 
    } 
    } 
}); 
+0

但我需要獲取陣列輸入的所有輸入 –

+0

已更新,以解決輸入數組。 –

0

這對我的作品

$(document).on('keypress',function(){ 
var inputs = $('input, select, textarea').one("keypress",function (e) { 
    if (e.which == 13) { 
    if($(this).attr('data-format')){ 
     formatNumber($(this)); 
    } 
    e.preventDefault(); 
    var nextInput = inputs.get(inputs.index(this) + 1); 
    if (nextInput) { 
     nextInput.focus(); 
    } 
    } 
}); 

});

+0

我不認爲這是你想要的解決方案。你仍然在處理器中綁定處理程序。 –