当用户使用 Jquery 按 Enter 键时,我目前正在尝试关注下一个输入类型。但是,由于某种原因,它不会检测到按键。
输入类型位于名为 mGrid 的 css 类中。
function addFocusSupport() {
$(".mGrid").find('input').each(function (index, element) {
// Here we get all the TextFields
alert($(this));
$(this).on("keypress",
function (e) {
if (e.KeyCode() === 13) {
// Focus next textfield
alert("Enter Pressed");
var nextElement = $('[index="' + (this.Index + 1) + '"]');
nextElement.focus();
alert(nextElement);
e.preventDefault();
}
// TODO: For last TextField, do nothing
});
});
}
所以我想做的是:用户填写第一个输入,按 Enter 键,将自动选择下一个文本框。将其视为按下的选项卡。
但是if (e.KeyCode() === 13) {
之后的事件从未触发?
就我而言,以下代码工作正常。
$('body').on('keydown', 'input, select', function(e) {
if (e.which === 13) {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
}
return false;
}
});
更改:
if (e.KeyCode() === 13) {
自:
if (e.which === 13) {
KeyCode()
不是获取密钥代码的正确方法。您正在考虑event.keyCode
,它已被弃用。如果您使用的是jQuery,则event.which
被规范化以适用于所有浏览器。如果没有 jQuery,请确保检查所有情况:
var key = event.which || event.charCode || event.keyCode
要聚焦下一个输入元素,请执行以下操作:
$(this).next('input').focus();
您可以使用以下代码
$(function() {
$(".mGrid >input").off('keyup').on('keyup', function(e) {
if (e.which === 13) {
$(this).next('input').focus();
}
});
});
这是一个有效的 Jsfiddle 演示
希望这对你有帮助