使用按键模拟输入填充 [英] input fill with keypress simulation

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

问题描述

假设我们有输入,我们想要添加一些文字。

Let's say we have an input and we want to add some texts to it.

 <form>
First name:<br>
<input type="text" id="thename" name="firstname">
</form> 

简单的方法是使用经典的element.value ...为输入添加值。
但是如果我想通过模拟按键事件来添加例如'David'呢?

The simple thing is to add value to input with classic element.value... . But what if I want to add for example 'David' by simulating the keypress event?

我遵循了以下几种方法:

I followed several approaches like this:

function simulateKeyEvent(character) {
  var evt = document.createEvent("KeyboardEvent");
  (evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
                    0, 0, 0, 0,
                    0, character.charCodeAt(0)) 
  var canceled = !body.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

取自在哪里并阅读几乎所有解决方案,但它们不起作用。

Taken from here and read almost every solutions but they didn't work.

注意:我在Firefox和Chrome中工作

Note: I'm working in Firefox and Chrome

推荐答案

已经回答此处

出于安全原因,您不是允许触发将导致文本填充输入的事件。请参阅链接答案中的变通办法。

For security reasons, you are not allowed to fire an event that will cause text to populate an input. See workarounds in the linked answer.

这篇关于使用按键模拟输入填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆