为什么这个 Javascript 没有在第二次鼠标悬停时成功更改背景?

Why doesn't this Javascript succesfully change the background on the second mouseover?

该函数应该在每次启动时将 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;