2013-08-05 25 views
1

我試圖獲取一組輸入之間的輸入索引。基本上,我有一個表格,其中包含多行輸入。jQuery - 獲取<input>引發按鍵事件的索引

一旦用戶按下「enter」按鈕,在輸入焦點時,我需要跳轉到下一個輸入字段,如「tab」鍵。

我下面this接受響應,這是我到目前爲止已經完成的:Fiddle

CODE

$(document).keypress(function(e){ 
    if(e.which == 13 && e.target.nodeName == 'INPUT'){ 
     var inputs = $("#inputsTable input.td_in"); 
     alert(inputs.index(this)); 
    } 
}); 

,你可以看到,每次集中輸入然後按ENTER,彈出msg說「-1」。

我在做什麼錯?我一直在爲這段代碼掙扎一個小時,而我放棄了。


我發現與e.target更換this也適用。

CODE

$(document).keypress(function(e){ 
    if(e.which == 13 && e.target.nodeName == 'INPUT'){ 
     var inputs = $("#inputsTable input.td_in"); 
     alert(inputs.index(e.target)); 
    } 
}); 

回答

2

這是因爲this引用document,不是你input

使用.on(),並把它傳遞一個input.td_in選擇:

$('#inputsTable').on('keypress', 'input.td_in', function (e) { 
    if(e.which == 13) { 
     var inputs = $("#inputsTable input.td_in"); 
     alert(inputs.index(this)); 
    } 
}); 

附:你應該可能是cache that selector

+0

感謝您的回覆!我發現也使用「e.target」而不是「this」適用於我的示例。 – BeNdErR

0
$(document).on('keypress', 'input', function (e) { 
    if(e.which == 13){ 
     var inputs = $("#inputsTable input"); 
     var the_index = inputs.index(this);   
     inputs[the_index+1].focus(); 
    }  
}); 

http://jsfiddle.net/5DwHw/1/