我制作了这个代码,以不同的间隔显示不同的交通信号灯。它可以工作,但是当我运行代码时,它从第二个图像开始。
"red-yellow 2.jpg"
我显然希望红绿灯从我的第一张图片开始,但我不知道问题是什么。
代码:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Code</h1>
<p>Traffic Light</p>
<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>
<script>
var list = [{
src: "only red1.jpg",
interval: 10000
}, {
src: "red-yellow 2.jpg",
interval: 5000
}, {
src: "green3.jpg",
interval: 3000
}, {
src: "yellowonly4.jpg",
interval: 1000
}];
var nextlight = 0;
var timer;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
var obj = list[nextlight];
firstlight.src = obj.src;
//firstlight.alt = obj.src;
timer = setTimeout(ChangeLight, obj.interval);
}
ChangeLight();
</script>
</body>
</html>
答案 0 :(得分:0)
你的功能应该是这样的,
function ChangeLight() {
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
var obj = list[nextlight];
firstlight.src = obj.src;
//firstlight.alt = obj.src;
timer = setTimeout(ChangeLight, obj.interval);
nextlight++;
}
答案 1 :(得分:0)
这可能听起来很愚蠢,但你试过吗
<img id="traffic" src="red1.jpg">
这可能是因为“only”可以被视为一个类。 也避免图像中的空格。使用hypen而不是
答案 2 :(得分:0)
您需要放下行nextlight = nextlight + 1;
,最终代码将是这样的
function ChangeLight() {
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
var obj = list[nextlight];
firstlight.src = obj.src;
nextlight = nextlight + 1;
//firstlight.alt = obj.src;
timer = setTimeout(ChangeLight, obj.interval);
}