简体   繁体   中英

JavaScript change img src

I am trying to make an image slider just using JavaScript. I have a button with an id in HTML and want to change the src of the button based on a position in an array. This is my following code.

var index = 0;
var imageArray = [{'images/img1.jpg'},{'images/img2.jpg'},{'images/img3.jpg'},{'images/img4.jpg'}];

function moveToNextSlide()
{
    if (index >= imageArray.length -1)
    {
        index =-1;
    }
    var img = getElementById(img_start);
    index = index + 1;
    var currentSlide = imageArray[index];
    getElementByid(img_start).src="currentSlide";

}

Looks like you're trying to create an array of strings. You have:

var imageArray = [{'images/img1.jpg'},{'images/img2.jpg'},{'images/img3.jpg'},{'images/img4.jpg'}];

Braces ( {} ) are used to declare objects ; the braces you have around each string are a syntax error. For just an array of strings, simply leave the quoted literals without braces:

var imageArray = ['images/img1.jpg','images/img2.jpg','images/img3.jpg','images/img4.jpg'];

There are a few issues. Firstly, you need to use the correct array syntax.

var imageArray = ['images/img1.jpg','images/img2.jpg','images/img3.jpg','images/img4.jpg'];

Also, you need to use document.getElementById and set as getElementById on it's own will refer to the window , not the document .

Finally, you need to set to the variable currentSlide like so img.src= currentSlide; , not "currentSlide" as a string.

function moveToNextSlide(){
    if (index >= imageArray.length -1){
        index =-1;
    }
    var img = document.getElementById('img_start');
    index = index + 1;
    var currentSlide = imageArray[index];
    img.src= currentSlide;
}

See full example here

 var index = 0; var imageArray = ['http://www.profightdb.com/img/wrestlers/thumbs-600/1414330df8brethart.jpg', 'http://armpit-wrestling.com/wp-content/uploads/2016/06/bret-hart.jpg']; document.body.onload = function(){ document.getElementById('img_start').src = imageArray[0]; }; function moveToNextSlide() { if (index >= imageArray.length - 1) { index = -1; } var img = document.getElementById('img_start'); index = index + 1; var currentSlide = imageArray[index]; img.src = currentSlide; } 
 img { max-width: 100px; } p { cursor: pointer; } 
 <img id="img_start" src=""> <p onclick="moveToNextSlide()">Click Here</p> 

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