现在我想制作一个 Web 程序,当我按下键盘时,我将全局变量的值更改为 1,如果不是,则设置为 0 。但不知何故,我无法使用 addEventlistener 进行更改这是我的代码:
<script>
var count;
function down(e) {
console.log("down");
count = 1 ;
// body...
}
function up(e) {
console.log("up");
count = 0;
}
window.addEventListener("keydown", down);
window.addEventListener("keyup", up);
document.getElementById('demo').innerHTML = count;
//somehow the output is always undefined instead of 1 or 0 , even though the
//function is executed
</script>
</body>
</html>
你已经快到了。您只需要做两件事:
- 为
count
指定默认值。当页面加载时,可能没有按键被按住,所以 0 是一个不错的选择。 - 每次事件发生时更新 DOM。因此,您需要在两个事件侦听器中调用
document.getElementById('demo').innerHTML = count
。
完成此操作后,它应该会更新您想要的方式:
// Give count a default value.
var count = 0;
function down(e) {
console.log("down");
count = 1;
document.getElementById('demo').innerHTML = count;
// body...
}
function up(e) {
console.log("up");
count = 0;
document.getElementById('demo').innerHTML = count;
}
window.addEventListener("keydown", down);
window.addEventListener("keyup", up);
// The html won't update automatically, so we have to manually update it each
// time the count is changed. Hence this line is duplicated in both event listeners.
document.getElementById('demo').innerHTML = count;
<div id="demo"></div>
我认为您缺少在事件更改时更新 dom。以下解决方案将为您工作。
function down(e) {
console.log("down");
count = 1 ;
document.getElementById('demo').innerHTML = count;
// body...
}
function up(e) {
console.log("up");
count = 0;
document.getElementById('demo').innerHTML = count;
}