【问题标题】:Jquery: On enter focus next inputJquery:在输入焦点下一个输入
【发布时间】:2017-10-11 07:36:17
【问题描述】:

当用户使用 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
  • keyCode 不是函数。所以请使用e.keyCode

标签: javascript jquery


【解决方案1】:

在我的例子中,以下代码运行良好。

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

【讨论】:

  • 当输入不是同级时就像一个魅力。
【解决方案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();

【讨论】:

  • 谢谢。这会触发警报。所以事件被按下。现在我只需要调试为什么它没有把重点放在下一个 txtbox
  • @Катерина 很高兴听到。我已经更新了关于关注下一个文本框的答案。
  • 我已将其切换到事件,尽管焦点对我不起作用
  • @Катерина 你能告诉我们你当前的代码吗? $(this).next('input') 将找到 this 的直接兄弟。你的输入元素是兄弟姐妹吗?
【解决方案3】:

你可以使用下面的代码

$(function() {
  $(".mGrid >input").off('keyup').on('keyup', function(e) {
    if (e.which === 13) {
      $(this).next('input').focus();
    }
  });
});

这里是一个工作 Jsfiddle demo

希望对你有帮助

【讨论】:

  • 非常感谢。我看到代码中的某个地方还有其他问题,因为小提琴工作正常!
猜你喜欢
  • 2017-02-10
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 2011-03-10
  • 1970-01-01
相关资源
最近更新 更多