简体   繁体   中英

JavaScript - Create an ad that changes every 3s using a switch statement

I need to create an ad that changes pictures automatically after every 3 seconds. This is what I have so far but I am stuck of where to go and how to finish: 1. Declare a variable named currentImage set equal to 1. 2. Declare a variable named autoAdvance and set it to run the ChangeAd() function every 3 seconds. 3.Create a function named ChangeAd(). 4.Within the function, use a case structure to determine the next ad to be displayed. -Use the currentImage variable in the switch statement. -For case 1: set the source of the first img element to "concert2.gif" then set the currentImage variable to 2. -For case 2: set the source of the first img element to "concert3.gif" then set the currentImage variable to 3. -For case 3: set the source of the first img element to "concert4.gif" then set the currentImage variable to 4. -For case 4: set the source of the first img element to "concert5.gif" then set the currentImage variable to 5. -For case 5: set the source of the first img element to "concert1.gif" then set the currentImage variable to 1. Remember to include break statements where needed.

[edit]

 <p><img src="concert1.gif" id="img" height="60" width="370" alt="Changing advertising image" /></p>
 <script>
  "use strict";
  var currentImage = 1;
  var autoAdvance = setInterval(ChangeAd, 3000);

  function ChangeAd(currentImage) {
  var image = document.getElementsByTagName("img");
     switch(currentImage){
        case 1:
           currentImage = 2;
           return "concert2.gif";
           break;
        case 2:
           curentImage = 3;
           return "concert3.gif";
           break;
        case 3:
           currentImage = 4;
           return "concert4.gif";
           break;
        case 4:
           currentImage = 5;
           return "concert5.gif";
           break;
        case 5:
           currentImage = 1;
           return "concert1.gif";
           break;
     }

  } 
 </script>

This should work. I made an array with all the image paths, and it just cycles over them. You should probably use something other than getElementsByTagName maybe use getElementById instead

var images = ["concert2.gif", "concert3.gif", "concert4.gif", "concert5.gif", "concert1.gif"];
var image = document.getElementsByTagName("img");
var currentImage = 0;

var autoAdvance = setInterval(ChangeAd, 3000);

function ChangeAd() {
    image.src= images[currentImage];
    currentImage ++;
    if(currentImage == images.length) currentImage = 0;
}

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