为什么不模拟tab键按键将焦点移动到下一个输入字段? [英] Why doesn't simulating a tab keypress move focus to the next input field?
问题描述
请注意此问题。我看到除了触发tab buttonpress事件之外还有其他方法,但我仍然想知道为什么触发tab键按下事件不会将焦点移动到下一个输入字段。
Note this question. I see that there are other approaches besides just triggering the tab keypress event, but I'd still like to know why triggering the tab key press event doesn't move focus to the next input field.
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
JS
$('textarea').on('keydown', function(e) {
if (e.metaKey && e.which === 40) {
console.log('test');
$(this).trigger({
type: 'keypress',
which: 9
});
}
});
推荐答案
因为标签事件是本机浏览器事件/操作改变焦点。 .trigger()
函数仅触发分配给它的事件处理程序。请注意, jQuery的网站提供了更多信息:
Because the tab event is a native browser event/action for changing focus. The .trigger()
function only triggers the event handlers that are assigned to it. Note there is more information given from jQuery's site:
.trigger()函数不能用于模仿本机浏览器事件,例如单击文件输入框或锚标记。这是因为,没有使用与这些事件对应的jQuery事件系统附加事件处理程序。
The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.
有一个插件,虽然叫做 jquery-simulate 来处理这个问题。可以说,标签
键更改焦点实际上是Web浏览器中的默认操作。触发浏览器本机事件并不意味着它会执行默认操作,因为 KeyboardEvents 提到:
There is a plug-in for this though called jquery-simulate to handle this. That being said the tab
key changing focus is actually a default action in the web browser. Firing a browsers native event does not mean it will do it's default action, as the documentation for KeyboardEvents mentions:
请注意,手动触发事件不会生成默认操作与该事件相关联。例如,手动触发键事件不会导致该字母出现在焦点文本输入中。在UI事件的情况下,出于安全原因这很重要,因为它可以防止脚本模拟与浏览器本身交互的用户操作。
Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. 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.
这篇关于为什么不模拟tab键按键将焦点移动到下一个输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!