我想捕获 TAB 按键,取消默认操作并调用我自己的 javascript 函数。
jQuery:如何在文本框中捕获 TAB 按键
IT技术
javascript
jquery
2021-02-20 13:11:36
6个回答
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');
}
});
在 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");
}
}
});
其它你可能感兴趣的问题