首页 > 解决方案 > 按键功能在javascript中不起作用

问题描述

我正在尝试并且必须keypress使用 JavaScript 写字母“A”。在下面的代码中,有一个alert('hello')框表示代码正在执行。

但是这段代码没有为“登录电子邮件”输入(这是一个文本框)设置任何值。

代码有什么问题?

          function presskey()
          { 
              var e = document.createEvent('KeyboardEvent');
              if (e.initKeyboardEvent)
              {
                  alert('hello'); e.initKeyboardEvent('keypress', true, true, document.defaultView, 'A', 0, '', false, '');
              }
              document.getElementById('login-email').dispatchEvent(e);
          }

标签: javascriptkeypress

解决方案


首先,我想指出的.initKeyboardEvent()是 deprecated。您可能想要的是事件构造函数(例如,对于“输入”事件,new InputEvent(),如下面的代码所示)

也就是说,我的其余答案假设问题实际上应该是“如何手动触发文本框上的输入事件?”。如果这实际上不是您想要的,请告诉我,但相同的概念应该适用于其他类型的事件。

...如果这是您的实际问题,我可以向您展示我将如何开始解决此问题:

const typeInto = (el, data) => {
  // Note the use of the InputEvent constructor
  const e = new InputEvent('input', {
    inputType: 'insertText',
    data,
  })
  
  // Manually add the text to element.value
  el.value += data
  
  // Fire the event like you were doing
  el.dispatchEvent(e)
}

// Get element
const el = document.querySelector('.js-login-email')

// Add an event listener for the 'input' event, to prove it's working
el.addEventListener('input', e => {
  console.log(`${e.inputType}: ${e.data}`)
})

// Example "typeInto" usage: call for each letter in the string below
'example@example.com'.split('').forEach(letter => {
  typeInto(el, letter)
})
<input type="email" class="js-login-email"/>


推荐阅读