繁体   English   中英

addEventListener回调中使用的变量未定义

[英]Variable used in addEventListener callback is undefined

在以下情况下,如何在addEventListener回调函数中提供testvar的新值? 在以下情况下, testvar的值未定义。

var testvar;
setTimeout(function(){
  var testvar = "testvar value"; 
 }, 3000);

document.querySelector('#anotherButton').addEventListener('click', ()=>{
  console.log('testvar '+testvar);
});

testvar局部声明隐藏了全局声明。

 var testvar = "Old value"; setTimeout(function(){ // Here just reuse the global declaration. testvar = "testvar value"; }, 3000); document.querySelector('#anotherButton').addEventListener('click', ()=>{ console.log('testvar: '+ testvar); }); 
 <button id="anotherButton">Click me!</button> 

var testvar = ...

您刚刚声明了一个新的局部变量。 它与您从未设置的其他变量完全无关。

您需要删除setTimeout方法内的var符号

var testvar;
setTimeout(function(){
  testvar = "testvar value"; 
 }, 3000);

声明的变量被约束在声明它们的执行上下文中。

var testvar; // default value undefined 

重新声明了testvar变量,其范围现在在该函数内

setTimeout(function(){
var testvar = "testvar value"; // testvar value and its scope is within this set
 }, 3000);

因此,在setTimeout函数之外,testVar变量值未定义

为了达到预期效果,请删除var,并使其成为全局testVar变量以返回值- “ testvar值”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM