jQuery:如何捕获文本框中的TAB键

我想捕捉TAB按键,取消默认动作,并调用我自己的JavaScript函数。

编辑:因为你的元素是dynamic插入的,所以你必须像在你的例子中一样使用委托on() ,但是你应该将它绑定到keydown事件,因为@Marc注释,在IE中,keypress事件不会捕获非字符键:

 $("#parentOfTextbox").on('keydown', '#textbox', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); // call custom function here } }); 

在这里检查一个例子。

jQuery 1.9中的工作示例:

 $('body').on('keydown', '#textbox', function(e) { if (e.which == 9) { e.preventDefault(); // do your code } }); 
 $('#textbox').live('keypress', function(e) { if (e.keyCode === 9) { e.preventDefault(); // do work } }); 

上面显示的方法没有为我工作,可能是我使用旧的jQuery,然后最后下面显示的代码段的作品 – 发布,以防万一有人在我的相同位置

 $('#textBox').live('keydown', function(e) { if (e.keyCode == 9) { e.preventDefault(); alert('tab'); } }); 

在选项卡上使用按键的一个重要部分是知道该标签将始终尝试做一些事情,不要忘记在最后“返回false”。

这是我做的。 我有一个在.blur上运行的函数和一个交换表单焦点的函数。 基本上它增加了一个input到表单的末尾,并在模糊运行计算时进入。

 $(this).children('input[type=text]').blur(timeEntered).keydown(function (e) { var code = e.keyCode || e.which; if (code == "9") { window.tabPressed = true; // Here is the external function you want to call, let your external // function handle all your custom code, then return false to // prevent the tab button from doing whatever it would naturally do. focusShift($(this)); return false; } else { window.tabPressed = false; } // This is the code i want to execute, it might be different than yours function focusShift(trigger) { var focalPoint = false; if (tabPressed == true) { console.log($(trigger).parents("td").next("td")); focalPoint = $(trigger).parents("td").next("td"); } if (focalPoint) { $(focalPoint).trigger("click"); } } }); 

尝试这个:

 $('#contra').focusout(function (){ $('#btnPassword').focus(); }); 

假设你有TextBox和Id txtName

 $("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });