简体   繁体   中英

Cannot display images stored in array automatically in JavaScript

I am trying to create webpage where the user clicks a button and then the page displays images saved in an array.When I run the code, It displays the source of the images, but not the images. Any tips on what I am doing wrong? Thanks in advance

<!DOCTYPE html>
<html>
<body>

<h1>Slideshow</h1>

<p>Holiday Slideshow</p>


<button type="button" onclick="beginShow()">View Slideshow</button>

<p id="p1"><img id="pic1" src="./assets/pic1.jpg">
Click on "View Slideshow". Click to display slideshow</p>
<script>
var list = [
    "/assets/pic1.jpg",
    "/assets/pic2.jpg",
    "./assets/pic3.jpg",
    "./assets/pic4.jpg"
];

var index = 0;

function beginShow() {
    setTimeout(myTimeout1, 2000) 
    setTimeout(myTimeout2, 4000) 
    setTimeout(myTimeout3, 6000)
    setTimeout(myTimeout4, 8000) 
}
function myTimeout1() {
    document.getElementById("p1").innerHTML = list[0];
}
function myTimeout2() {
    document.getElementById("p1").innerHTML = list[1];
}
function myTimeout3() {
    document.getElementById("p1").innerHTML = list[2];
}
function myTimeout4() {
    document.getElementById("p1").innerHTML = list[3];
}
</script>

    </body>
</html>

You need to set those urls to the image instead of its container.

Your code should be written like this.

var list = [
    "/assets/pic1.jpg",
    "/assets/pic2.jpg",
    "./assets/pic3.jpg",
    "./assets/pic4.jpg"
];
function showImage(i){
    i = i || 0;
    setTimeout(function(){
        document.getElementById("pic1").src = list[i];
        i < list.length - 1 && showImage(++i);
    },2000);
}
showImage();

If you are going to do it this way you have to change what you assign to innerHTML:

document.getElementById("p1").innerHTML = '<img src=' + list[0] + '>;

But I recommend you rather change src attribute of image to list[0]:

document.getElementById('pic1').setAttribute('src', list[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