在JS / jQuery中触发keypress / keydown / keyup事件? [英] Trigger a keypress/keydown/keyup event in JS/jQuery?
问题描述
模拟用户在JS和/或jQuery的文本输入框中输入文本的最佳方法是什么?
我不想要实际将文本放在输入框中,我只想触发通常由用户在输入框中键入信息而触发的所有事件处理程序。这意味着焦点,keydown,按键,键盘和模糊。我认为。
那么如何实现这一目标?
你可以触发直接打电话给他们的任何事件,如:
$(function(){
$( 'item')。keydown();
$('item')。keypress();
$('item')。keyup();
$('item')。 blur();
});
这样做你想做什么?
您可能还应触发 .focus()
并可能 .change()
如果你想用特定的键触发键事件,你可以这样做:
$(function(){
var e = $ .Event('keypress');
e.which = 65; //字符'A'
$(' item')。trigger(e);
});
这里有一些关于按键事件的有趣讨论: jQuery的事件按键:?哪个键被按下,特别是关于与财产。其中跨浏览器的兼容性。 p>
What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?
I dont 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();
});
Does that do what you're trying to do?
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);
});
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屋!