用 jQuery 模拟按 Tab 键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9214125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:30:31  来源:igfitidea点击:

Simulate pressing tab key with jQuery

jquerykeydownsimulate

提问by AGuyCalledGerald

I have some textboxes on a .net-page and want to achieve the following with jQuery: if the user presses return, the program should behave "as if" he had used the tab key, thus, selecting the next element. I tried the following code (and some more):

我在 .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>

but it just does not work! Missing something, making a mistake?

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

Here some links I used

这是我使用的一些链接

here

这里

and here

和这里

采纳答案by czerasz

Try this:

尝试这个:

http://jsbin.com/ofexat

http://jsbin.com/ofexat

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

or the loop version: http://jsbin.com/ofexat/2

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

回答by Mark Lagendijk

I created a simple jQuery pluginwhich does solve this problem. It uses the ':tabbable' selector of jQuery UI to find the next 'tabbable' element and selects it.

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

Example usage:

用法示例:

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

回答by Shehbaz

From multiple answers I have combined the perfect solution for me where enter acts as tab on inputs and select and takes focus on next input, select or textarea while allows enter inside text area.

从多个答案中,我为我组合了完美的解决方案,其中 enter 充当输入上的选项卡,然后选择并关注下一个输入、选择或 textarea,同时允许在文本区域内输入。

 $("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();
     }
 });

回答by Shai Mishali

Try this

尝试这个

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