曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
Web前端

Pitfalls of Simulating Keyboard Input with JS

Pitfalls At first I searched around on Google and found a jQuery solution. The amount of code was small, it looked great and promising, but it didn't work at all…… I tried these versions over and over: var e = $.Event('keyup') e.keyCode = 49 $('#btn').trigger(e) // just replace keycode with which $('#btn').trigger($.Event('keyup', { which: 4

曦远 (DealiAxy)约 7 分钟
目录4 个章节

Pitfalls

At first I searched around on Google and found a jQuery solution. The amount of code was small, it looked great and promising, but it didn't work at all……

I tried these versions over and over:

var e = $.Event('keyup')
e.keyCode = 49
$('#btn').trigger(e)
// 就是把 keycode 换成 which
$('#btn').trigger($.Event('keyup', { which: 49 }))

Didn't work at all……

Then I looked at the event listener in the developer debugging tools and found that the input box was listening for the input event. So I tried setting the input's value first, then using jQuery to simulate triggering the event to see if it would work~

$('#btn').trigger('input')

That didn't work either

Solution

Then I found a pretty good method: using native JS InputEvent. For older Chrome, use UIEvent instead; the effect is basically the same.

The code is as follows

Using InputEvent:

var dom = document.querySelector('#selector')
var evt = new InputEvent('input', {
    inputType: 'insertText',
    data: st,
    dataTransfer: null,
    isComposing: false
});
dom.value = '输入的内容';
dom.dispatchEvent(evt);

Using UIEvent:

var dom = document.querySelector('#selector')
var evt = new UIEvent('input', {
    bubbles: false,
    cancelable: false
});
dom.value = st;
dom.dispatchEvent(evt);

Personally tested, it works perfectly

You can wrap it into a function yourself for more convenient calling; I won't paste that part of the code~

References

Welcome to Discuss

Programming Lab focuses on exploring popular new internet technologies and team agile development practices. Reply with linux, flutter, c#, netcore, android, kotlin, java, python, etc. in the backend of the WeChat official account "Programming Lab" to get related technical articles and materials. If you have any questions, you can also leave a message in the official account backend~

_EOF_

Pitfalls of Simulating Keyboard Input with JS

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…