Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用带有3幅图像的SetaAttribute的交通灯_Javascript_Image_Onclick_Attributes_Setattribute - Fatal编程技术网

Javascript 使用带有3幅图像的SetaAttribute的交通灯

Javascript 使用带有3幅图像的SetaAttribute的交通灯,javascript,image,onclick,attributes,setattribute,Javascript,Image,Onclick,Attributes,Setattribute,我需要帮助我的任务做交通灯使用设置属性和交通灯的3个图像 这就是我到目前为止所做的: <img src="theImage" alt="red.jpg"> <p><input type="button" id="theButton" value="click me!" onclick="pictureChange()"></p> 根据Google Chrome控制台,第18行是错误的,但我找不到解决此问题的方法。在设置的属性中,需要将灯光加上引

我需要帮助我的任务做交通灯使用设置属性和交通灯的3个图像

这就是我到目前为止所做的:

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

<p><input type="button" id="theButton" value="click me!" onclick="pictureChange()"></p>

根据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
}

我这样做了,但当我按下按钮时,图像没有改变,控制台中没有语法错误,但仍然不起作用?这不是语法错误,你的代码只是没有做你想要的。我已经更新了我的答案,它应该对你有帮助。好的,谢谢,它起作用了,但是你有没有网页或者什么东西可以告诉我这一切是如何工作的?非常感谢,这需要练习。如果你刚开始的话,我建议使用codeaccademy.com。但大部分都是边走边学。选择此作为结束此问题的答案。好的,非常感谢您的帮助,这对我帮助很大,现在我不必向朋友寻求帮助,并尝试在接下来的2天内完成代码。:)