红绿灯使用 setAttribute 和 3 个图像

Traffic lights using setAtrribute with 3 images

我需要帮助来完成使用设置属性和 3 个交通信号灯图像制作交通信号灯的任务。

这是我目前拥有的:

<img src="theImage" alt="red.jpg">

<p><input type="button" id="theButton" value="click me!" onclick="pictureChange()"></p>
var lights = ["red.jpg", "amber.jpg", "green.jpg"]

function pictureChange(){
  // line 18:
  document.getElementById("theImage").setAttribute(lights, "amber.jpg");
}

根据 Google Chrome 控制台,第 18 行是错误的,但我找不到解决此问题的方法。

在您的设置属性中,您需要将灯放在引号中。这是一个字符串属性名称。

document.getElementById('theImage').setAttribute('lights','amber.jpg');

编辑: 现在我看了一下,我认为您希望交通灯随着每次单击该按钮而改变。这就是我要做的

var lights = ["red.jpg","amber.jpg","green.jpg"]
var lightCounter=0;
function pictureChange(){
lightCounter+=1; //Increase the lightCounter by 1;
 document.getElementById('theImage').src=lights[lightCounter];//Set the source of the image to be an element in the array pointed at by the light counter
}