Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Simulating a Keypress Event from Javascript Console

I want to simulate a Keypress event using the Javascript Console. I see lots of answers using an input element. I don't want to use an input element. I just want to paste some code into the Javascript console and have a keypress event simulated(specifically the back space button).

Answers using jQuery are welcome.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

jQuery has a .keypress method accepting no arguments that simulates a keypress.

$("#target").keypress();

Will trigger a keypress on #target

If you'd like to also select which key was pressed, you can use .trigger. This example is from the docs:

var e = $.Event("keydown", { keyCode: 8}); //"keydown" if that's what you're doing
$("body").trigger(e);

The key code 8 is the key code for backspace in JavaScript.

Let me know how that works for you :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...