gpt4 book ai didi

javascript - Esc 事件监听器不起作用

转载 作者:行者123 更新时间:2023-12-03 03:57:51 30 4
gpt4 key购买 nike

我已经添加了按键监听器,但这不起作用。当“click”的监听器被调用时 - 工作完美。

这是代码:

var closeSave = document.getElementById("closeSave");
closeSave.addEventListener("click", closeWindow);
closeSave.addEventListener("keypress", closeWindowByEsc);

// When the user clicks on <span> (x), close the modal
var closeWindow = function() {
saveModal.style.display = "none";
loadModal.style.display = "none";
}

var closeWindowByEsc = function(){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '27'){
closeWindow(e);
}
}

可能是什么问题?

最佳答案

问题在于声明 var func = function () { ...var func; 部分提升到作用域的顶部,但是 func在到达该行之前, 不会被定义为 function () { ...。因此,当您附加事件处理程序时,基本上会发生以下情况:

var closeSave = document.getElementById("closeSave");
var closeWindow;
var closeWindowByEsc;

// here, closeWindow and closeWindowByEsc are `undefined`
closeSave.addEventListener("click", closeWindow);
closeSave.addEventListener("keypress", closeWindowByEsc);

// When the user clicks on <span> (x), close the modal
closeWindow = function() {
saveModal.style.display = "none";
loadModal.style.display = "none";
}

closeWindowByEsc = function(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '27') {
closeWindow();
}
}

您可以做两件事来解决这个问题:

addEventListener() 移至实例化下方:

var closeSave = document.getElementById("closeSave");

// When the user clicks on <span> (x), close the modal
var closeWindow = function() {
saveModal.style.display = "none";
loadModal.style.display = "none";
}

var closeWindowByEsc = function(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '27') {
closeWindow();
}
}

closeSave.addEventListener("click", closeWindow);
closeSave.addEventListener("keypress", closeWindowByEsc);

或者您可以使用将实例化提升到作用域顶部的函数语句,而不是函数表达式:

var closeSave = document.getElementById("closeSave");

closeSave.addEventListener("click", closeWindow);
closeSave.addEventListener("keypress", closeWindowByEsc);

// When the user clicks on <span> (x), close the modal
function closeWindow() {
saveModal.style.display = "none";
loadModal.style.display = "none";
}

function closeWindowByEsc(e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '27') {
closeWindow();
}
}

关于javascript - Esc 事件监听器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44857419/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com