首页 > 解决方案 > 如何从javascript中的事件处理程序内部修改外部变量?

问题描述

我有一个带有点击事件监听器的按钮

let button = document.createElement('button');
let show = false;
button.addEventListener('click', (e) => {
     e.stopPropagation();
     show = !show;
     console.log("show from inside:", show)
});
console.log("show from outside:", show) // => is always equal to false

show但是上面的这一行仍然显示与初始化时相同的变量值。

我怎样才能show像这一行一样从内部修改变量show = !show并在这一行从外部获取该修改console.log("show from outside:", show)

标签: javascriptvariablesscopeevent-handling

解决方案


您已创建元素但未将其附加到主体/父节点。您需要将以下行添加到您的代码中。

document.body.appendChild(button);

如果您需要获取修改后的show值,您可以编写一个函数来返回值show并在您想要的任何地方使用它。

最终代码:

let button = document.createElement('button');
document.body.appendChild(button);

let show = false;
function getShow() { return show; } // => returns the latest value of show

button.addEventListener('click', (e) => {
     e.stopPropagation();
     show = !show;
     console.log("show from inside:", getShow());
});
console.log("show from outside:", getShow()); // => Keep in mind that this line will run before the event handler does and only for once.

希望这可以帮助!


推荐阅读