【发布时间】:2021-06-22 19:59:41
【问题描述】:
我编写了这个短代码来显示一个将背景颜色更改为蓝色的按钮。在我点击按钮之前背景颜色会改变,我只是不知道为什么,在我点击按钮之前背景不应该默认为白色吗?
//function to change background color
function changeBg(color) {
document.body.style.backgroundColor = color;
}
// goBlue closure
var goBlue = changeBg("blue");
// create button
var blueButton = document.createElement("button");
blueButton.innerHTML = "Blue";
// add button to page
var body = document.getElementsByTagName("body")[0];
body.appendChild(blueButton);
//add event listener
blueButton.addEventListener("click", goBlue);
感谢您的帮助
【问题讨论】:
-
与您的帖子有些无关,但您应该停止使用“var”并使用“let”。我看不出 var 的意义是什么,考虑到变量具有全局范围,并且您的代码与根本不输入“var”是一样的。 “let”更好,因为它创建了一个“块范围的局部变量”
标签: javascript background-color