我正在尝试并且必须使用 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/