我正在制作计算器应用程序,我在文档中添加了一个事件监听器,以监听数字按键,例如:
function listenForKeyPress() {
// add document event listener for all key presses
document.addEventListener('keyup', (e) => {
// check to see if the keypress was a number
if (/[0-9-+-\--.]/g.test(e.key)) {
// check to see if the input is not already focused
if (document.activeElement !== input) {
// focus element
input.focus();
// focus value
input.value += e.key;
}
}
})
}
// call function
listenForKeyPress();
问题是,当我使用F5刷新页面时,将F5输入到输入元素中,如下所示:
我如何防止这种情况的发生,在此先感谢。
仅匹配一个字符,以^开头,以$结尾,并删除全局/ g标志