上記のコードを少し改善しました。コードの問題は、入力フィールド内を移動できないことです。たとえば、'100.00|' の値があります。現在カーソルが最後にあります (| で示されます)。左キーを押すと、キャレットを「100.0 | 0」の位置に移動する代わりに、前の入力フィールドにジャンプします。
そのためには、e.target.selectionStart で現在のキャレットの位置を確認する必要があります。ただし、前のキャレット位置も必要です。そうしないと、キャレットが 1 から 0 に移動したか (ジャンプなし)、またはキャレットが既に 0 にあり、ユーザーがもう一度左を押した (ジャンプ) かを識別できません。
私が追加したもう 1 つの変更は、クラス tableInput を持つ入力フィールドのみが考慮されることです。一部のフィールドを除外したい場合。
function(e){
var charPos = e.target.selectionStart;
var strLength = e.target.value.length;
var prevPos = $(this).data('prevPos');
if(e.which==39){
//only go right if we really reached the end, that means the prev pos is the same then the current pos
if(charPos==strLength && (prevPos ==null || prevPos == charPos)){
$(this).closest('td').next().find('input.tableInput').focus();
$(this).data('prevPos',null);
}else{
$(this).data('prevPos',charPos);
}
}else if(e.which==37){
//only go left if we really reached the beginning, that means the prev pos is the same then the current pos
if(charPos == 0 && (prevPos ==null || prevPos == charPos)){
$(this).closest('td').prev().find('input.tableInput').focus();
$(this).data('prevPos',null);
}else{
$(this).data('prevPos',charPos);
}
}else if(e.which==40){
$(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input.tableInput').focus();
$(this).data('prevPos',null);
}else if(e.which==38){
$(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input.tableInput').focus();
$(this).data('prevPos',null);
}
});