ESC按键甚至没有被捕获

问题描述 投票:0回答:2

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

这是代码:

var closeSave = document.getElementById("someId");
    closeSave.addEventListener("keypress", func);

            // When the user clicks on <span> (x), close the modal    
    var func = function(){
    if (!e) e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == '27'){
      closeWindow(e);
    }
  }
    

可能是什么问题?

javascript addeventlistener
2个回答
2
投票

问题在于,声明

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

0
投票

您没有将事件

e
传递给您的函数。

var closeSave = document.getElementById("closeSave");
closeSave.addEventListener("click", closeWindow);
closeSave.addEventListener("keypress", function(e){
    if (!e) e = window.event;
    var keyCode = e.keyCode;
    if (keyCode == '27'){
        closeWindow();
    }
});

// When the user clicks on <span> (x), close the modal
function closeWindow() {
    saveModal.style.display = "none";
    loadModal.style.display = "none";
}
© www.soinside.com 2019 - 2024. All rights reserved.