我添加了按键监听器,但这不起作用。 当“点击”的听众被调用时 - 工作正常。
这是代码:
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);
}
}
可能是什么问题?
答案 0 :(得分:1)
问题是声明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();
}
}
答案 1 :(得分: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";
}