Answers:
编辑:由于元素是动态插入的,因此您必须像示例中那样使用委托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
}
});
e.preventDefault();
双防止插入空白文本框成。
$('#textbox').live('keypress', function(e) {
if (e.keyCode === 9) {
e.preventDefault();
// do work
}
});
使用选项卡上的向下键的重要部分是知道选项卡将始终尝试做某事,不要忘了最后“返回假”。
这是我所做的。我有一个在.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");
}
}
});
您可以使用此 JQuery API 捕获事件选项卡。
$( "#yourInputTextId" ).keydown(function(evt) {
if(evt.key === "Tab")
//call your function
});