我对上面的代码略有改进。代码的问题是您无法在输入字段内导航。例如,您的值为 '100.00|' 光标当前位于末尾(用 | 表示)。如果按左键,它将跳转到上一个输入字段,而不是将插入符号移动一个位置到“100.0|0”。
为此,您需要使用 e.target.selectionStart 检查当前插入符号的位置。但是您还需要 prev 插入符号位置,否则您无法确定插入符号是从 1 变为 0(无跳转)还是插入符号已经位于 0 并且用户再次按下左键(跳转)。
我添加的另一个更改是只考虑具有类 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);
}
});