Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

javascript - 触发JS / jQuery中的keypress / keydown / keyup事件?(Trigger a keypress/keydown/keyup event in JS/jQuery?)

What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?(模拟用户在JS和/或jQuery中的文本输入框中输入文本的最佳方法是什么?)

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?(那么,一个人如何做到这一点呢?)   ask by Alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()(您可能还应该触发.focus()并可能触发.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?(这里有一些有关按键事件的有趣讨论: jQuery Event按键:按下了哪个键?) , specifically regarding cross-browser compatability with the .which property.(,特别是与.where属性的跨浏览器兼容性。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...