我已经添加了按键监听器,这是行不通的。
当调用“ 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/

10-11 23:29
查看更多