[英]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.