[英]Function isn't working with a gobal variable. Should it be expected?
正如标题所说,我不能在我的 function 上使用变量“countDash”,如果它是全局的,只能是本地的。 应该是这样吗?
我错过了什么? 提前致谢。
//count
let countEl = document.getElementById("count-el");
let saveEl = document.getElementById("save-el");
let count = 0;
//message to user
let username = "Mr. Unknown";
let message = "You have three new notifications";
let messageToUser = `${message}, ${username}!`;
//welcome message
let welcomeEl = document.getElementById("welcome-el");
let name = "Eduardo";
let greeting = "Welcome back";
welcomeEl.innerHTML = `${greeting}, ${name}!`;
function increment() {
count += 1;
countEl.innerHTML = count;
}
// let countDash = ` ${count} -`; //does not work
function save() {
let countDash = ` ${count} -`; //it only works if I have it here localy
saveEl.innerHTML += countDash;
}
当您在全局 scope 中声明 CountDash 时,代码只运行一次,因此 CountDash 使用值“0 -”进行初始化。 因此,即使您在增量 function 中更新计数,countDash 也不会更新。 如果您出于某种原因想要将 countDash 保留为全局变量(尽管我们应该尽可能减少全局变量的使用),您可以在更新增量 function 的计数后更新它:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.