gpt4 book ai didi

javascript - 如何使我的交通灯序列中的颜色发生变化

转载 作者:行者123 更新时间:2023-11-28 01:14:20 24 4
gpt4 key购买 nike

在这段代码中,第一个红色交通灯出现,但当我点击按钮时它不会改变。是的,我知道有类似的问题,但它们似乎没有帮助。因此,如果您能告诉我哪里出了问题,我将不胜感激。

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Task 3</h1>

<p>This is my Traffic Light script</p>

<img id = "light" src="Red Traffic light.jpg">

<button type="button" onclick="changeLights()">Change Lights</button>

<script>
var list = [
"Red Traffic light.jpg",
"Red & Yellow Traffic light.jpg",
"Green Traffic light.jpg",
"Yellow Traffic light.jpg"
];

var index = 0;

function changeLights() {

index = index + !
if (index == list.length - 1) {
index = 0;
}

var image = document.getElementById("light");
image.src=list[index];

</script>

最佳答案

我已在我的答案中添加评论以显示更改。

  1. 您还没有关闭 changeLights() 函数。
  2. index+! 好像打错了,用index++加1。
  3. 更改您的 if 语句,因为它缺少最后一张图片。

var list = [
"http://imgur.com/FHT9OoG.jpg",
"http://imgur.com/XZ1PxGh.jpg",
"http://imgur.com/5DUX0Wy.jpg",
"http://imgur.com/WpeEMZU.jpg"
];
var index = 0;
function changeLights() {
index++ // Add 1 to index.
// If index is more than the array length, reset to 0
// Or you can use: if(index == list.length){
if (index > list.length-1){
index = 0;
}
var image = document.getElementById("light");
image.src=list[index];
}
<img id = "light" src="http://imgur.com/FHT9OoG.jpg">
<button type="button" onclick="changeLights()">Change Lights</button>

如果您有任何问题,请在下方留言,我会尽快回复您。

希望对您有所帮助。编码愉快!

关于javascript - 如何使我的交通灯序列中的颜色发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36364702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com