javascript - 按键功能在 JavaScript 中不起作用

标签 javascript keypress

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

但是此代码不会为“login-email”输入(这是一个文本框)设置任何值。

代码可能有什么问题?

          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);
          }

最佳答案

首先,我想指出 .initKeyboardEvent() is 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"/>

关于javascript - 按键功能在 JavaScript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947132/

相关文章:

python - 使用按键重新启动 While 循环

javascript - D3 具有相同颜色点的多折线图

javascript - 如何使用 DropzoneJs 发送身份验证 token header ?

javascript - 在 Wordpress 中使用 PJAX

python - 如何在 Python/PyQt 中模拟真实键盘的按键?

java - android-如何检测服务中的按键?

javascript - 如何为只有下一个/上一个选项的非常简单的分页创建 Angular Directive(指令)/服务

javascript - 无限滚动 + 砌体 = 不工作

javascript - jQuery Focus() 或 keypress() 在 IE 和 Chrome 中不起作用

jquery - 你能在 jQuery/javascript 中将 ctrl 和 mouseenter 结合起来吗?