如何使用jQuery模拟输入字段中的输入? [英] How to simulate typing in input field using jQuery?
问题描述
我想要的是使用javascript模拟< input>
字段中的输入。
What I want is to simulate typing in <input>
field using javascript.
我有以下代码:
var press = jQuery.Event("keydown");
press.ctrlKey = false;
press.which = 65;
$("#test").trigger(press);
但是当我加载页面时, #test
输入字段没有打字字符,'65'的键码代表'A',但没有'A'输入。
But when I load the page, the #test
input field has no typed characters, the keycode of '65' represents 'A', but there is no 'A' input.
基本上我想要的是使用Greasemonkey自动在网站上输入内容。
Basically what I want is to automatically typing in the website using Greasemonkey.
请给我一些想法或一些我可以用来做这个的图书馆。
非常感谢!
Please give me some ideas or some library with which I can use to do this.
Thanks a lot!
推荐答案
你可以发送关键事件,听取它们的任何内容都会得到它们,但它们不会改变输入,所以你例如,不会看到字母 A
。这主要是安全的事情;请参阅手动触发事件以进行讨论。
You can send key events, and anything listening for them will get them, but they will not change the input, so you will not see the letter A
appear, for example. This is mostly a security thing; see "Manually firing events" for a discussion about that.
因此,如果您希望显示该字母,则必须在发送密钥事件时更改输入的值。有一个jQuery插件,请参阅 $ .fn.sendkeys
插件。
So, if you want the letter to appear, you must alter the input's value as you send the key event. There is a jQuery plugin for that, see "The $.fn.sendkeys
Plugin".
你可以看到< input>
对用户应用的密钥,关键事件以及 this jsFiddle 中的插件做出反应。
You can see how an <input>
reacts with user-applied keys, key events, and that plugin at this jsFiddle.
作为参考,这是来自jsFiddle的关键代码:
For reference, this is the key piece of code from that jsFiddle:
$("button").click ( function (zEvent) {
if (zEvent.target.id == "simA_plain") {
console.log ("Send Plain key event");
var keyVal = 65;
$("#eventTarg").trigger ( {
type: 'keypress', keyCode: keyVal, which: keyVal, charCode: keyVal
} );
}
else {
console.log ("Use the Plugin to simulate a keystroke");
$("#eventTarg").sendkeys ("B") ;
}
} );
如果你只是试图在< input>
上模拟输入,该插件应该足够了。但是,根据您真正尝试做的事情,您可能需要执行以下一项或多项操作:
That plugin should be sufficient if you are just trying to "simulate typing on an <input>
". However, depending on what you are really trying to do, you may need to do one or more of the following:
- 只需将文字设置为您想要的文本。
- 如果页面的javascript触发,则发送
keydown
事件 - 同样,如果页面的javascript触发了该事件,则发送
更改
事件等。 - 只需找到并直接调用页面的javascript即可。使用脚本注入,位置黑客,
unsafeWindow
和/或@grant none
模式来做到这一点。 - 还有别的吗?说明您的真实目标并链接到目标页面。
- Just set the text to what you want it to be.
- Send a
keydown
event, if the page's javascript triggers off of that. - Likewise, send a
change
event, etc., if the page's javascript triggers off of that. - Just find and call the page's javascript directly. Use script injection, the location hack,
unsafeWindow
, and/or@grant none
mode to do that. - Something else? State your true objective and link to the target page.
这篇关于如何使用jQuery模拟输入字段中的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!