简体   繁体   中英

How to make the colours change in my traffic light sequence

In this code, the first red traffic light shows up, but it won't change when I click the button. Yes, I know there are similar questions like this one, but they don't seem to help. So if you could tell me what's wrong I would really appreciate it.

<!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>

I have added comments into my answer to show the changes.

  1. You haven't closed the changeLights() function.
  2. index+! appears to be a typo, use index++ to add 1.
  3. Changes to your if statement as it's missing the last image.

 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>

If you have any questions please leave a comment below and I will get back to you as soon as possible.

I hope this helps. Happy coding!

Do you mean to increment index by 1 within changeLights() ? Looks like you're adding a ! to index instead, turning it into a string.

Additionally you're not closing the changeLights() function (you've closed the if conditional only).

Check your console to see if there's an error message when you click the button.

The debugger in firefox gives these errors:

SyntaxError: expected expression, got keyword 'if' lights.html:27:4 a bit cryptic, so we look at what precedes it and see that we have typed ! instead of 1 , so we fix it, and try again.

SyntaxError: missing } after function body lights.html:32:25 so we fix it, and try again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM