如何使用addEventListener更改函数内的全局变量的值?

时间:2018-01-04 01:18:52

标签: javascript global-variables

现在我想创建一个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>

2 个答案:

答案 0 :(得分:0)

你已经快到了。你只需要做两件事:

  • count一个默认值。当页面加载时,可能没有按下任何键,因此0是一个不错的选择。
  • 每次事件发生时更新DOM。因此,您需要在两个事件侦听器中调用document.getElementById('demo').innerHTML = count

完成后,它应该更新您想要的内容:

&#13;
&#13;
// 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;
&#13;
<div id="demo"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为您在事件发生变化时更新了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;

}