2017-04-09 39 views
0

错误在于图像没有改变。该代码不会替换下一个状态的交通灯的图像。谁能帮忙? 我遇到了我的程序错误。错误是(我认为)正在改变图像的来源。

<!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> 

回答

1

声明一个新变量

var lightIndex =0; 

和 在MainSequence功能使用这样的:

lightIndex = (lightIndex +1)%LightStates.length; 
image.src = LightStates[lightIndex ]; 
0

你的问题是,您对您的每一次MainSequence函数运行整个循环叫做。你当前的实现看到当前状态为0,然后切换到1,然后看到当前状态为1,然后切换到2等,直到它回到0.然后有2000毫秒的时间间隔。我建议,宣布了新的变数:

var lightNumber = 0; 

,然后改变你的MainSequence的要简单得多:

function MainSequence(){ 
    lightNumber++; 
    if (lightNumber > 3){ 
     lightNumber = 0; 
    } 
    image.src = lightStates[lightNumber]; 
} 
相关问题