使用jQuery模拟按Tab键

时间:2012-02-09 15:52:03

标签: jquery keydown simulate

我在.net页面上有一些文本框,并希望用jQuery实现以下功能:如果用户按下返回,程序应该“好像”他使用了tab键,因此,选择下一个元素。我尝试了以下代码(以及更多代码):

<script type="text/javascript">

jQuery(document).ready(function () {

    $('.tb').keypress(function (e) {
        if (e.keyCode == 13)
        {
            $(this).trigger("keydown", [9]);
            alert("return pressed");
        } 
    });
});

<asp:TextBox ID="TextBox1" runat="server" CssClass="tb"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" CssClass="tb"></asp:TextBox>

但它不起作用!错过了什么,犯了错误?

这里有一些我用过的链接

here

and here

4 个答案:

答案 0 :(得分:15)

试试这个:

http://jsbin.com/ofexat

$('.tg').bind('keypress', function(event) {
  if(event.which === 13) {
    $(this).next().focus();
  }
});

或循环版本:http://jsbin.com/ofexat/2

答案 1 :(得分:11)

我创建了一个simple jQuery plugin来解决这个问题。它使用jQuery UI的':tabbable'选择器来查找下一个'tabbable'元素并选择它。

使用示例:

// Simulate tab key when enter is pressed           
$('.tb').bind('keypress', function(event){
    if(event.which === 13){
        if(event.shiftKey){
            $.tabPrev();
        }
        else{
            $.tabNext();
        }
        return false;
    }
});

答案 2 :(得分:9)

从多个答案中我结合了完美的解决方案,输入作为选项卡上的选项并选择并关注下一个输入,选择或文本区域,同时允许输入内部文本区域。

 $("input,select").bind("keydown", function (e) {
     var keyCode = e.keyCode || e.which;
     if(keyCode === 13) {
         e.preventDefault();
         $('input, select, textarea')
         [$('input,select,textarea').index(this)+1].focus();
     }
 });

答案 3 :(得分:4)

试试这个

$(this).trigger({
    type: 'keypress',
    which: 9
});
相关问题