简体   繁体   中英

Replace image with JavaScript on timer

I am really new to JavaScript and working on a project to replace an image every 5 seconds without using a onClick command.

The first function startAdPage should start when the page loads, allowing the setInterval commands inside that function to begin. Once the changeAd function starts it is supposed to replace the image in the table with the matching id.

I would really appreciate some advice. Some that may be a problem which I am not sure about is I have the Javascript contained in the body of my document, but the onLoad at the start of the body. Is that an issue as well?

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>CVR1</title> </head> <body onLoad="startAdPage()"> <script type="text/javascript"> /* <![CDATA[ */ function startAdPage() { setInterval(changAd,5000); } function changeAd() { //THIS NEEDS WORK should change the image every 5 seconds to replace the one in the table document.getElementById("adImage").src = images[index]; index = (index + 1) % images.length; } /* ]]> */ </script> <table> <tr> <td><img id="adImage" src="pictures/cvb1.gif" ></td> <td><p>Advertisement</p><p>The Central Vally Realtors home page will be displayed in TEXTFIELD seconds.</p><p><a href="CVR2.html">Skip Advertisement</a></p></td> </tr> </table> </body> </html> 

On this line:

setInterval(changAd,5000);

changAd should be changeAd

Remember to press F12 and check the console for errors, you have:

Uncaught ReferenceError: changAd is not defined

As the comments show there also seem to be other essential parts missing: the images array and index is undefined.

var index = 0;

var images = [
    'image1.png',
    'image2.png'
];

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