javascript 如何使用Javascript将键发送到输入文本字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7062367/
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
How to send a key to an input text field using Javascript?
提问by Arian
How I can send a combination of keys (like Ctrl+C or Alt+Shift) when cursor goes in a input text field using Javascript?
当光标进入使用 Javascript 的输入文本字段时,如何发送组合键(如 Ctrl+C 或 Alt+Shift)?
I'm not using jQuerybut am using MS-Ajax. Is it possible using MS-Ajax DOM?
我没有使用 jQuery,而是使用 MS-Ajax。是否可以使用 MS-Ajax DOM?
EDIT 1)
编辑 1)
According to @Ghostoy help,I wrote this code:
根据@Ghostoy 的帮助,我写了这段代码:
function simulateKeyPress() {
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress", true, true, window,
0, 0, 0, 0,
0, "e".charCodeAt(0))
var canceled = !body.dispatchEvent(evt);
if (canceled) {
alert("canceled");
} else {
alert("not canceled");
}
}
but when called it I got an error:
但是当我调用它时,我得到了一个错误:
Error: Object doesn't support property or method 'initKeyEvent'
and then I changed the KeyboardEvent
to KeyEvents
I got this error:
然后我将其更改KeyboardEvent
为KeyEvents
我收到此错误:
Error: DOM Exception: NOT_SUPPORTED_ERR (9)
where is my fault?
我的错在哪里?
采纳答案by Ghostoy
Simulate key events is not easy. See this question: Simulating user input for TDD JavaScript. You'd better try other workarounds.
模拟关键事件并不容易。请参阅此问题: 模拟 TDD JavaScript 的用户输入。您最好尝试其他解决方法。
回答by ryamx
Change
evt.initKeyEvent(...)
to
evt.initKeyboardEvent(...)
更改
evt.initKeyEvent(...)
为
evt.initKeyboardEvent(...)
or change to jQuery :)
或更改为 jQuery :)
回答by bresleveloper
there is an asnwer! we only need to extend the JQ Event with all its needed attributes, see here: http://bresleveloper.blogspot.co.il/2013/03/jsjq-simulate-enter-event.html
有一个答案!我们只需要使用其所有需要的属性来扩展 JQ 事件,请参见此处:http: //bresleveloper.blogspot.co.il/2013/03/jsjq-simulate-enter-event.html
回答by ghayes
You cannot trigger key events as if a user has actually pressed the key. See herefor a relevant question. You can trigger events for your own bindings
, like so (JSFiddle here, copied from answer shown above):
您不能像用户实际按下按键一样触发按键事件。有关相关问题,请参见此处。您可以为自己触发事件bindings
,如下所示(此处为JSFiddle ,从上面显示的答案中复制):
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);