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

Jon*_*son 140 javascript jquery

我想捕获TAB按键,取消默认操作并调用我自己的javascript函数.

CMS*_*CMS 241

编辑:由于您的元素是动态插入的,您必须在示例中使用委托on(),但是您应该将其绑定到keydown事件,因为在@Marc注释时,在IE中,按键事件不会捕获非字符键:

$("#parentOfTextbox").on('keydown', '#textbox', function(e) { 
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { 
    e.preventDefault(); 
    // call custom function here
  } 
});
Run Code Online (Sandbox Code Playgroud)

点击这里查看示例.

  • @AppleGrew:它是这样说的,是的,但事实并非如此 - 至少对于按键来说.对于Tab e.which为0而e.keyCode为9(应该是).在FF 3.5.16,jQuery 1.6.2中测试. (5认同)

Buz*_*zlo 17

jQuery 1.9中的工作示例:

$('body').on('keydown', '#textbox', function(e) {
    if (e.which == 9) {
        e.preventDefault();
        // do your code
    }
});
Run Code Online (Sandbox Code Playgroud)

  • make`e.preventDefault();`double以防止在文本框中插入空格. (2认同)

Jon*_*son 12

$('#textbox').live('keypress', function(e) {
    if (e.keyCode === 9) {
        e.preventDefault();
        // do work
    }
});
Run Code Online (Sandbox Code Playgroud)

  • ^^具有讽刺意味...... jQuery应该弥合broswers之间的差距,这样你就不必担心这样的事情. (4认同)
  • 另外,要取消默认操作,请使用e.preventDefault(); 在函数的第一行. (2认同)

Oxi*_*Oxi 7

上面显示的方法对我来说不起作用,可能是我使用了一点旧的jquery,然后最后显示的代码片段适用于 - 发布以防万一我处于相同的位置

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


小智 5

在 tab 上按下键的一个重要部分是知道 tab 总是会尝试做一些事情,不要忘记在最后“返回 false”。

这是我所做的。我有一个在 .blur 上运行的函数和一个交换表单焦点所在位置的函数。基本上它会在表单的末尾添加一个输入,并在运行模糊计算时进入那里。

$(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");
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)