2
Heyo,有人可以向我解釋爲什麼如果變量'white'在函數內部時這個代碼不起作用嗎?變量不能在函數裏
var button = document.querySelector("button");
var body = document.querySelector("body");
var white = true;
button.addEventListener("click", function() {
if (white) {
body.style.backgroundColor="pink";
} else {
body.style.backgroundColor="white";
}
white = !white;
});
你瞭解可變範圍嗎? – Carcigenicate
它可以工作,但每次點擊時它總是被定義爲「true」。所以,絕大多數函數的代碼永遠不會發生 – Anarion
[JavaScript中的變量範圍是什麼?]的可能重複(https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in -javascript) –