jQuery:按下回车键聚焦到下一个输入框

3

我目前正在尝试使用Jquery,在用户按下回车键时将焦点集中在下一个输入类型上。但是,由于某种原因,它无法检测到按键。

这些输入类型位于名为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
            });
    });
}

我正在尝试的是: 用户填写第一个输入框,按下回车键后自动选择下一个文本框。可以将其视为按下制表符。
但是在if (e.KeyCode() === 13) {之后的事件从未被触发?

它是 e.keyCode 减去 k - sheplu
keyCode不是一个函数。所以使用e.keyCode - prasanth
3个回答

6

在我的情况下,以下代码可以正常运行。

$('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;
  }
});

当输入不是兄弟节点时,它的工作效果非常好。 - Maddie

2

更改:

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();


谢谢。这会触发警报。所以事件被按下了。现在我只需要调试为什么它没有将焦点放在下一个文本框上。 - Катерина
@Катерина 很高兴听到这个消息。我已经更新了关于下一个文本框的重点的答案。 - Michael Auderer
我已经将它切换为事件,尽管焦点对我来说并不起作用。 - Катерина
@Катерина,你能展示一下你当前的代码吗?$(this).next('input')将找到this的直接兄弟节点。你的输入元素是兄弟节点吗? - Michael Auderer
https://stackoverflow.com/questions/46687825/asp-jquery-focus-next-textbox-from-gridview - Катерина

1
你可以使用以下代码。
$(function() {
  $(".mGrid >input").off('keyup').on('keyup', function(e) {
    if (e.which === 13) {
      $(this).next('input').focus();
    }
  });
});

这里有一个可工作的Jsfiddle 演示

希望这能帮到你


非常感谢。我看到代码中还有其他地方出了问题,因为这个示例能正常工作! - Катерина

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接