<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id="D:\ComputerScience\JavaScriptExtras\RedLights.jpg" src=D:\ComputerScience\JavaScriptExtras\RedLights.jpg>
<button type="button" onclick="ChangeLights()">ChangeLights</button>
<script>
var list = ["D:\ComputerScience\JavaScriptExtras\RedLights.jpg", "D:\ComputerScience\JavaScrip tExtras\RedAmberLights.jpg", "D:\ComputerScience\JavaScriptExtras\GreenLights.jpg", "D:\ComputerScience\JavaScriptExtras\AmberLights.jpg"]
var count: 0, 1
function ChangeLights() {
var image = document.getElementById('D:\ComputerScience\JavaScriptExtras\RedLights.jpg');
}
if list = 0 {
image.src = list[0];
}
if list = 1 {
image.src = list[1];
} else if list = 2 {
image.src = list[2];
} else >3 {
image.src = list[3];
}
}
</script>
</body>
</html>
我正在查看我的代码,它会运行并向我显示正确的灯光,但是它不会从红色变为其他任何东西。当我在谷歌浏览器上运行错误代码时,它表示没有定义转换灯。我已经盯着代码好几天了,如果有人知道为什么转换灯没有被定义,那就永远感谢你。如果你能为我整理代码,那将非常感激
答案 0 :(得分:0)
您的代码中确实存在很多语法错误,很难说代码应该实现什么。我做了很多改变以使它工作,但只是猜测它现在做了你想要它做的事情:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id="lightimg" src="file:///D:/ComputerScience/JavaScriptExtras/RedLights.jpg">
<button type="button" onclick="ChangeLights()">ChangeLights</button>
<script>
var list = [
"file:///D:/ComputerScience/JavaScriptExtras/RedLights.jpg",
"file:///D:/ComputerScience/JavaScriptExtras/RedAmberLights.jpg",
"file:///D:/ComputerScience/JavaScriptExtras/GreenLights.jpg",
"file:///D:/ComputerScience/JavaScriptExtras/AmberLights.jpg"
];
var count = 0;
function ChangeLights() {
var image = document.getElementById('lightimg');
image.src = list[count];
count++;
if (count >= list.length)
count = 0;
}
</script>
</body>
</html>
这些是我改变的一些事情:
list
中的ChangeLights
变量的比较。id
标记的img
更改为“lightimg”以避免ID名称中的反斜杠file:///
)