【问题标题】:How to navigate from one textbox to another textbox using arrow keys如何使用箭头键从一个文本框导航到另一个文本框
【发布时间】:2017-09-28 12:15:11
【问题描述】:

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

提前致谢。这是我写的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/

【问题讨论】:

  • 你基本上是在问如何从你的代码中删除.parent() ...
  • 请将您的 HTML 添加到问题中
  • 你试过标签索引了吗?
  • @SumeetGohil:标签索引工作正常。但我只需要使用箭头键在文本框之间切换。

标签: javascript jquery navigation


【解决方案1】:

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

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"),并根据按下的按钮增加/减少相关索引,您将能够找到新的索引。使用新索引,您只需在matrix 中与新索引对应的元素上添加.focus()。不过要注意越界问题。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2020-01-22
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多