程序不起作用,我不知道为什么

时间:2017-02-17 10:45:51

标签: javascript html

我正在制作一个应该在网页上显示按钮和彩色圆圈的脚本。按下此按钮时,应该更改圆的颜色。有3种颜色应该循环,因此每次按下按钮时它们都应该按顺序改变。

问题是,当我运行我的代码时,它只显示我在制作代码时选择的彩色圆圈,而当我按下按钮时不会改变。

这是我的代码:

<!doctype html>
<html>
<head>
   <title>Traffic Lights</title>
</head>
<body>
   <img id="trafficimg" src="green.jpg"  alt="Change Now!">
   <button type="button" onClick="changelight()"> Change the Lights! </button>
   <script>
      var assets = ["red.jpg","yellow.jpg","green.jpg"]
      var state = 1
      var colour = ""                
      function changelight() {
         if state == 1{
            var colour = "green";
         if state == 2{
            var colour = "orange";
         if state == 3{
            var colour = "red";
      }                                
      if colour.includes("green"){
         document.getElementById("trafficimg").setAttribute('src', assets[0]);
         state=state+1;
         if colour.includes("green"){
            document.getElementById("trafficimg").setAttribute('src', assets[1]);
            state=state+1;
            if colour.includes("green"){
               document.getElementById("trafficimg").setAttribute('src', assets[2]);
               state=state - 2;
            }
         }
      }       
   </script>
</body>
</html>

如果可能的话,我会帮助获得不会过多更改代码的简单解决方案,但是,我们非常感谢任何帮助。谢谢大家。

2 个答案:

答案 0 :(得分:4)

您需要将条件包装在括号中

if (state == 1) {
// ^          ^
    colour = "green";
    // no need to redeclare color
}
// missing curly bracket at the end of if statement

使用state作为图像数组索引的工作示例。

var assets = ["https://dummyimage.com/50x50/F00/000000&text=+", "https://dummyimage.com/50x50/FF0/000000&text=+", "https://dummyimage.com/50x50/0F0/000000&text=+"],
    state = 0;

function changelight() {
    state++;                // increment state
    state %= assets.length; // remainder operator for keeping state in range of array
    document.getElementById("trafficimg").setAttribute('src', assets[state]);
}
<img id="trafficimg" src="https://dummyimage.com/50x50/F00/000000&text=+" alt="Change Now!"><br>
<button type="button" onClick="changelight()"> Change the Lights! </button>
     

答案 1 :(得分:0)

您的简短代码段中有多个错误(实际上很多)错误。顺便说一句,我想你想做到这一点:

var state = 1;
var colour = "green";

function changelight(state) {

    if (state == 1){color = "green";}
    if (state == 2){color = "orange";}
    if (state == 3){color = "red";}


    switch(color){
        case 'green': {document.getElementById("para1").style.background = 'green'; break;} 
        case 'orange': {document.getElementById("para1").style.background = 'orange'; break;}
        case 'red':{document.getElementById("para1").style.background = 'red'; break;}
    }

}
<p id="para1" style="background:green;width:50px;height:50px;border-radius:50%;"></p>
<button type="button" onClick="changelight(1)"> green</button>
<button type="button" onClick="changelight(2)"> orange</button>
<button type="button" onClick="changelight(3)"> red</button>