簡體   English   中英

Jquery:在輸入焦點下一個輸入

[英]Jquery: On enter focus next input

當用戶使用 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
            });
    });
}

所以我想要做的是:用戶填寫第一個輸入,按回車鍵並自動選擇下一個文本框。 將其視為按下的選項卡。

但是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演示

希望這會幫助你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM