错误是图像没有变化。代码不会用下一个状态替换交通灯的图像。有人可以帮忙吗?
<!DOCTYPE html>
<html>
<head>Traffic Lights</head>
<body onload = "setInterval(MainSequence(), 2000)">
<h1>Javascript Traffic Lights</h1>
<button onclick = "MainSequence()">Click here to change the lights</button>
<img id = "myImage" src = "RedLight.png" width = "270" height = "400"></img>
<script>
var LightStates = newArray("RedLight.png", "RedandAmberLight.png", "GreenLight.png", "AmberLight.png");
var image = document.getElementById("myImage");
function MainSequence(){
if (image.src === (LightStates[0])){
//changes the source of the image
image.src = LightStates[1];
return;
}
if (image.src === (LightStates[1])){
image.src = LightStates[2];
return;
}
if (image.src === (LightStates[2])){
image.src === LightStates[3];
return;
}
if (image.src === (LightStates[3])){
image.src = LightStates[0];
return;
}
};
</script>
</body>
</html>
答案 0 :(得分:1)
声明一个新变量
var lightIndex =0;
和 在MainSequence函数中使用如下:
lightIndex = (lightIndex +1)%LightStates.length;
image.src = LightStates[lightIndex ];
答案 1 :(得分:0)
您的问题是,每次调用MainSequence函数时都会运行整个循环。您当前的实现看到当前状态为0,然后切换为1,然后看到当前状态为1,然后切换到2等,直到它回到0.然后有2000ms的间隔。我建议声明一个新变量:
var lightNumber = 0;
然后将您的MainSequence更改为更简单的:
function MainSequence(){
lightNumber++;
if (lightNumber > 3){
lightNumber = 0;
}
image.src = lightStates[lightNumber];
}