2013-09-25 3 views
2

Я заинтересован в выполнении очень простой функции автоматической табуляции. Я хотел бы программным образом нажать «вкладку» для посетителя. Я не могу понять, как это сделать в стандартном JS (т. Е. Не использовать jQuery's .trigger()).Как имитировать нажатие клавиши тангажа с угловым

Использование: <input auto-tab="3">

directive('autoTab', [function() { 
     return { 
      restrict: "A", 
      scope: false, 
      link: function (scope, el, attrs) { 
       el.bind('keyup', function() { 
        if (el.val().length >= attrs.autoTab) { 
         //document.dispatchEvent(); 
        } 
       }); 
      } 
     } 
    }]) 

ответ

4

не думаю это можно. Проверьте this post и this SO question:

Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a focus event does not cause the element to receive focus (you must use its focus method for that), manually firing a submit event does not submit a form (use the submit method), manually firing a key event does not cause that letter to appear in a focused text input, and manually firing a click event on a link does not cause the link to be activated, etc. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

Вы можете попробовать другой подход: изменить директиву так он получает идентификатор элемента, который должен быть сосредоточен в следующем:

app.directive('autoTabTo', [function() { 
    return { 
    restrict: "A", 
    link: function (scope, el, attrs) { 
     el.bind('keyup', function(e) { 
     if (this.value.length === this.maxLength) { 
      var element = document.getElementById(attrs.autoTabTo); 
      if (element) 
      element.focus(); 
     } 
     }); 
    } 
    } 
}]); 

И тогда вы могли бы использовать его например:

<input type="text" id="input1" auto-tab-to="input2" maxlength="5"/> 
<input type="text" id="input2" auto-tab-to="input1" maxlength="3"/> 

Рабочая демонстрация here.

Это не совсем то, что вы хотите, но я боюсь, что это невозможно сделать, моделируя нажатие клавиши TAB.

+0

Если вы не используете элемент [0] .focus(), чтобы удалить зависимость JQuery? –

+0

@BrianF Вы правы. Я полностью пропустил это, когда отправил ответ. Исправит это. Благодаря! –

+0

@BrianF Я только что проверил его, и код прав: 'element' не является объектом jQuery, поэтому вызов' .focus() 'напрямую в порядке. –

-1

В зависимости от степени поддержки браузера вам нужно, dispatchEvent() может сделать трюк для вас.

1

я думаю, что это один не лучше, нет необходимости упоминать идентификатор для элемента ввода

app.directive('autoTabTo', [function() { 
    return { 
    restrict: "A", 
    link: function (scope, el, attrs) { 
    el.bind('keyup', function(e) { 
     if (this.value.length === this.maxLength) { 
       var inputs = $(this).closest('form').find(':input'); 
       inputs.eq(inputs.index(this)+ 1).focus(); 
     } 
     }); 
    } 
    } 
}]); 
+0

Хороший умный бит кода, но все еще имеет зависимость jQuery. Внутренняя часть может быть переписана следующим образом: 'var input = elem.closest ('form'). Find (': input'); inputs.eq (inputs.index (elem) + 1) .focus(); ' –

Смежные вопросы