javascript - 按键功能在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);
}
解决方案
首先,我想指出的.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"/>
推荐阅读
- java - 查找和更改元组值
- python - 没有名为“oauth2_provider.ext”的模块
- slatejs - Slatejs 如何使一个特定节点不可编辑?
- php - 找不到列,因为我的表中有不同的列名
- android - 如何将 webapp 和 android 应用与 firebase 连接?
- python - 使用 requests.get 从商店网站查找简单的产品信息
- php - 如何使用 XAMPP 启动 apache 服务器?
- abap - 想要显示结果列表中的所有行项目而不是最后一个行项目
- java - 如何将基于 JAVA6 EJB 的应用程序迁移到 OpenJDK 13?
- python - Python mysql命令不显示