【问题标题】:Jquery focus on next element with classJquery专注于类的下一个元素
【发布时间】:2012-10-31 13:17:42
【问题描述】:

我正在尝试创建一个函数,当按下 Enter 键时,会选择下一个带有类的输入。

我已经设法 .focus() 同一行中的下一个元素。但是,如果我需要在下一行选择下一个输入,则无法继续。

需要关注下一行中的第一个 .quantity 文本框。

控制台没有错误。

http://jsfiddle.net/FP6qa/

HTML

<table>
   <tr>
       <td>
         <input class='quantity' value=''/>
         <input class='100' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='50' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='20' value=''/>
       </td>
   </tr>
   <tr>
       <td>
         <input class='quantity' value=''/>
         <input class='100' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='50' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='20' value=''/>
       </td>
   </tr>
</table>

JQuery

 $(".quantity").on('keypress', function (e) {
        if (e.keyCode === 13) {
           $(this).parent().next('td').find('input.quantity').focus();
        }  
});

【问题讨论】:

  • 您有多个 quantity 文本框。下一行的哪个quantity 文本框应该有焦点?
  • 第一个。对不起,我会修改问题。我正在寻找模拟tabindex。

标签: jquery html next


【解决方案1】:

你可以使用index方法:

var $quan = $('.quantity');
$quan.on('keyup', function(e) {
    if (e.which === 13) {
        var ind = $quan.index(this);
        $quan.eq(ind + 1).focus()
    }
});

http://jsfiddle.net/cwgZP/

或者,如果您想选择所有输入,您可以尝试:

var $input = $('input[type=text]');
$input.on('keyup', function(e) {
    if (e.which === 13) {
        var ind = $input.index(this);
        $input.eq(ind + 1).focus()
    }
});  

【讨论】:

  • +1。第一种方法的效果几乎与我要发布的内容完全相同(除了我打算在一行中使用var $quantity = $('.quantity').on(...)。你甚至像我计划的那样将keyCode 更改为which...
  • @undefined 第一个解决方案很有效。但是,因为这是它在 keypress 事件上提交的表单的一部分,所以我添加了 return false;但它没有成功
  • @nnnnnn 谢谢,真是巧合。
  • @claw - 我认为表单是在 down 键上提交的,不是吗?如果是这样,取消键 up... 为时已晚
猜你喜欢
  • 1970-01-01
  • 2012-05-31
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多