如何使用箭头键从一个文本框导航到另一个文本框

时间:2017-09-28 12:15:11

标签: javascript jquery navigation

我可以使用向上和向下箭头键。但是有人可以解决如何使用向左和向右键移动到相邻的文本框。我使用了div而不是表标签。

提前致谢。这是我编写的JS代码。

 $("input").keydown(function (e) {                               
   switch (e.which) {
     case 39:
       break;
     case 37:
       break;
     case 40:
       $(this).parent().parent().next().find('input').focus()
       break;
     case 38:
       $(this).parent().parent().prev().find('input').focus()
       break;
   }
 });

小提琴示例:http://jsfiddle.net/cAyRs/747/

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以通过在数组数组中创建上下文来轻松解决此问题:

var matrix = [];
for (var i = 0; i < rowCount; i++) {
    var row = [];
    var rowInputs;
    //Somehow get the context of the inputs you have in the given row
    //Let's suppose it is inside an inputs array:
    for (var j = 0; j< inputs.length; j++) {
        row.push(inputs[j]);
        inputs[j].data("row-index", i).data("col-index", j);
    }
    matrix.push(row);
}

然后如果你能够分别阅读.data("row-index").data("col-index")并根据按下的按钮增加/减少相关索引,你就可以找到新的索引。使用新索引,您只需.focus()对应于新索引的matrix元素。但要注意出界问题。

相关问题