我的代码不起作用。红绿灯的颜色不会改变。请帮助我进行计算控制评估。
<!DOCTYPE HTML>
<html>
<body>
<h1> TRAFFIC LIGHTS </h1>
<img id="RED" src = "RED.jpg">
<script>
var lights = ["RED.jpg", "AMBER.jpg", "GREEN.jpg", "AMBER.jpg"]
var count = 0
function Changelights() {
document.getElementById("RED")src=lights[count]
count = count + 1
if(count === redlight.length){
count = 0;
}
}
</script>
<div>
<button type= "button" onclick= "Changelights()">Change Lights </button>
</div>
</body>
</html>
答案 0 :(得分:0)
您的代码段中有一些错误。
var light = document.getElementById("light")
。我还将id
重命名为light
以使其更明确,因为颜色会发生变化。src
方法更改setAttribute
属性。count
script
标记放在body
标记
<body>
<h1> TRAFFIC LIGHTS </h1>
<img id="light" src="http://faculty.washington.edu/miceal/lgw/red.JPG">
<div>
<button type= "button" onclick= "changeLights()">Change Lights </button>
</div>
<script>
var lights = ["http://faculty.washington.edu/miceal/lgw/red.JPG", "http://webyogi.co.uk/wp-content/uploads/2014/12/2880x1800-amber-orange-solid-color-background.jpg", "https://upload.wikimedia.org/wikipedia/commons/d/de/Color-Green.JPG"]
var count = 1 // So it turns amber on the first click
var light = document.getElementById("light")
function changeLights() {
light.setAttribute("src",lights[count++])
count = count === lights.length ? 0 : count; // If count is the length of the array, we're setting it to 0. Else, we're incrementing it (it's called a ternary).
}
</script>
</body>
答案 1 :(得分:-1)
<img id="RED" src = "RED.jpg">
<script>
var lights = ["RED.jpg", "AMBER.jpg", "GREEN.jpg", "AMBER.jpg"]
var color = document.getElementById("RED");
function Changelights()
{
for(var i = 0; i < lights.length; i++)
{
color.src=lights[i];
if(i == lights.length)
{
i = 0;
}
}
}
</script>