jQuery 从 Javascript 控制台模拟按键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15722096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simulating a Keypress Event from Javascript Console
提问by Philip Kirkbride
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).
我想使用 Javascript 控制台模拟 Keypress 事件。我看到很多使用输入元素的答案。我不想使用输入元素。我只想将一些代码粘贴到 Javascript 控制台中并模拟按键事件(特别是退格按钮)。
Answers using jQuery are welcome.
欢迎使用 jQuery 的答案。
回答by Benjamin Gruenbaum
jQuery has a .keypress
method accepting no arguments that simulates a keypress.
jQuery 有一种.keypress
不接受任何参数的方法来模拟按键操作。
$("#target").keypress();
Will trigger a keypress on #target
将触发按键 #target
If you'd like to also select which key was pressed, you can use .trigger
. This example is from the docs:
如果您还想选择按下了哪个键,您可以使用.trigger
. 这个例子来自文档:
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 backspacein JavaScript.
Let me know how that works for you :)
让我知道这对你有什么作用:)