2

我正在尝试创建一个函数,当按下 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();
        }  
});
4

1 回答 1

9

您可以使用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()
    }
});  
于 2012-11-12T04:12:30.210 回答