在 JS/jQuery 中触发 keypress/keydown/keyup 事件? [英] Trigger a keypress/keydown/keyup event in JS/jQuery?
问题描述
在 JS 和/或 jQuery 中模拟用户在文本输入框中输入文本的最佳方法是什么?
What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?
我不想实际将文本放入输入框中,我只想触发通常由用户输入信息触发的所有事件处理程序进入输入框.这意味着焦点、keydown、keypress、keyup 和模糊.我认为.
I don't want to actually put text in the input box, I just want to trigger all the event handlers that would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think.
那么如何做到这一点呢?
So how would one accomplish this?
推荐答案
您可以通过直接调用任何事件来触发它们,如下所示:
You can trigger any of the events with a direct call to them, like this:
$(function() {
$('item').keydown();
$('item').keypress();
$('item').keyup();
$('item').blur();
});
这是否符合您的要求?
您可能还应该触发 .focus()
和可能的 .change()
You should probably also trigger .focus()
and potentially .change()
如果你想用特定的键触发键事件,你可以这样做:
If you want to trigger the key-events with specific keys, you can do so like this:
$(function() {
var e = $.Event('keypress');
e.which = 65; // Character 'A'
$('item').trigger(e);
});
这里有一些关于按键事件的有趣讨论:jQuery 事件按键:按下了哪个键?,特别是关于与 .which 属性的跨浏览器兼容性.
There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.
这篇关于在 JS/jQuery 中触发 keypress/keydown/keyup 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!