javascript - 如何从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)
?
解决方案
您已创建元素但未将其附加到主体/父节点。您需要将以下行添加到您的代码中。
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.
希望这可以帮助!
推荐阅读
- python - 如何通读 CSV,然后在 Python 中发布批量 API 调用
- html - 上传前端图片 Wordpress
- javascript - Firefox 插件:gapi.client 未定义
- wordpress - VM 重新启动 Google Cloud Engine 后站点关闭
- kubernetes - 如何从 Helm 中的渲染中排除 CustomResourceDefinition?
- github - 如何解决对我的 GitHub 页面的推送更新?
- highlight - 突出重点节点
- javascript - 单击按钮后如何在 Stripe 中显示微调器?
- c# - 没有 MediaTypeFormatter 可用于从媒体类型为“application/xml”的内容中读取“MYAPI”类型的对象
- python - 如何在python中渲染\left(\right)