If statement 为什么';这个Javascript在第二次鼠标悬停时是否成功地改变了背景?

If statement 为什么';这个Javascript在第二次鼠标悬停时是否成功地改变了背景?,if-statement,onmouseover,If Statement,Onmouseover,该函数应该在每次启动时将x增加1,从而迫使代码在下次启动时选择不同的选项 function changeBackground() { var x = 0; if (x % 2 === 0) { document.getElementById("sample").style.backgroundColor = "purple"; } else { document.getElementById("sample").style.backgroundColor = "w

该函数应该在每次启动时将
x
增加1,从而迫使代码在下次启动时选择不同的选项

function changeBackground() {
  var x = 0;
  if (x % 2 === 0) {
    document.getElementById("sample").style.backgroundColor = "purple";
  }
  else {
    document.getElementById("sample").style.backgroundColor = "white";
  }
  x++;
}
var x = document.getElementById("sample");
x.onmouseover = changeBackground;

这只是抓取一个标题,并在每次光标置于标题上时启动
changeBackground
。背景色保持为紫色,因为每次在函数开始时都将其设置为0。。您需要在函数外部设置变量

var x = 0;
function changeBackground() {
if (x % 2 === 0) {
document.getElementById("sample").style.backgroundColor = "purple";
}
else {
document.getElementById("sample").style.backgroundColor = "white";
}
x++;
}
var x = document.getElementById("sample");
x.onmouseover = changeBackground;

因为每次在函数开始时都将其设置为0。。您需要在函数外部设置变量

var x = 0;
function changeBackground() {
if (x % 2 === 0) {
document.getElementById("sample").style.backgroundColor = "purple";
}
else {
document.getElementById("sample").style.backgroundColor = "white";
}
x++;
}
var x = document.getElementById("sample");
x.onmouseover = changeBackground;

这就是问题所在,谢谢。我还注意到我声明了两次x。这就是问题所在,谢谢。我还注意到我声明了x两次。