更新时间:2021-11-17 21:51:03
如果您正在尝试收听活动,请点击,那么你需要这样的东西:
If you're trying to listen for an event click, then you need something like this:
document.getElementById("BGchange").addEventListener("click", BGcolor);
然后,您需要修复此功能中的一些内容:
Then, you need to fix some things in this function:
function BGcolor (){
var BG = BG2+1
var BG2 = BG
if(BG==0){
document.body.style.background = white;
} else if (BG==1) {
document.body.style.background = black;
}
}
因为你试图引用 BG2
在它被初始化之前所以不清楚你想在那里做什么。
Because you are trying to reference BG2
before it has been initialized so it is not clear what you want to be doing there.
按顺序,我改变的事情:
In order, the things I changed:
获取按钮的DOM元素document.getElementById()
addEventListener()
这是添加事件处理程序的标准方法 BGcolor
而不显示parens。你是立即调用它而不是传递对稍后可以调用的函数的引用。document.getElementById()
addEventListener()
which is the standard way of adding event handlersBGcolor
without the parens. You were calling it immediately rather than passing a reference to the function that can be called later.此外,还有很多东西要做修复你的 BGcolor()
函数:
In addition, a bunch of things to fix in your BGcolor()
function:
white
,不是白色
。 backgroundColor
property。"white"
, not white
.backgroundColor
property.这是一个工作版本:
<button Id="BGchange">BUTTON!</button>
<script type="text/javascript">
document.getElementById("BGchange").addEventListener("click", BGcolor);
var curColor = "white";
function BGcolor (){
if (curColor == "white") {
curColor = "black";
} else {
curColor = "white";
}
document.body.style.backgroundColor = curColor;
}
</script>