本文介绍了Chrome:使用javascript模拟输入文本字段上的按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在堆栈溢出中有很多内容,但是似乎没有任何内容适用于我的情况.我有一个输入文本字段,我想模拟按键事件来填充文本字段.

There is a lot of contents on this in stack overflow but none seems to work for my case. I have an input text field and I want to simulate keypress event to fill the text field.

原因::我正在不提供API的Web界面上自动执行很多数据输入任务.使用.value更改输入字段不会触发接口的JS侧(角度).这就是为什么我要模拟按键事件.

Reason: I am automating a lot of data entry task on a web interface which provides no API. Changing the input field using .value does not trigger the JS side (angular) of the interface. That is why I want to simulate keypress event.

首先,我尝试了这个:

var inp = document.getElementById('rule-type');
inp.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));

然后我在Chrome中了解到keycode保持为0,在KeyBoardEvent中没有变化.

Then I learned in Chrome the key and code stays as 0 and does not change in KeyBoardEvent.

所以我创建了单独的事件ev = new KeyboardEvent('keypress',{'key':'a', 'code': 'KeyA'})

So I created seperate event ev = new KeyboardEvent('keypress',{'key':'a', 'code': 'KeyA'})

然后我再次调度,return语句是true,但它不会更改输入字段.

And then I dispatched again, the return statement is true but it does not change the input field.

解决方案需要使用纯JavaScript而不是jQuery.

The solution needs to be in pure javascript not jQuery.

推荐答案

您将无法触发将导致文本填充输入的事件.请参见 MDN :

You will not be able to fire an event that will cause text to populate an input. See this snippet from MDN:

感谢 @ gforce301

您最好的选择是设置值并然后调度事件.

Your best bet may be to set the value and then dispatch an event.

这篇关于Chrome:使用javascript模拟输入文本字段上的按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:40