我有兴趣做一个非常简单的自动标签功能。我想以编程方式为访问者按下“标签”。我似乎无法弄清楚如何在标准 JS 中实现这一点(即 - 不使用 jQuery 的 .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();
}
});
}
}
}])
最佳答案
我不认为这是可能的。退房 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.
您可以尝试不同的方法:更改您的指令,使其接收接下来应该关注的元素的 id:
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 击键来实现。
关于events - 如何模拟带有 Angular 的选项卡按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017064/