简体   繁体   中英

how can I adapt the following code to make i of the array increment on button click?

with the following code how can I increment the array based on onclick. I currently have this on a timer but want it to use the onclick option to change the picture/increment the array

   var i=0;
var images = [];
var time = 1000;

images[0] = 'img1.jpg';
images[1] = 'img2.jpg';
images[2] = 'img3.png';

//change image function
function changeIMG()
{
    document.slide.src = images[i];

    if(i < images.length - 1)
    {
        i += 1;
    }
    else
    {
        i = 0;
    }
    setTimeout("changeIMG()", time);
}
window.onload = changeIMG;

First, let's add the button:

<button id='btn'>Change Image</button>

Now, adding some JavaScript to handle the button's onclick event:

var btn = document.getElementById('btn');
btn.onclick = changeIMG;

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