简体   繁体   中英

Create a function to add an image to an array on click of button

I have a web page that displays an array of images of world leaders.

I need to add a button that will add an additional leader onto that array and display it as well.
If anyone could point me in the right direction, thanks in advance.

<button class="btn" id="addLeader">Add Leader</button>

</section>


<script type="text/javascript">

window.onload = function () {


    var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg'];  //array of images
    ArrayOfImages.forEach(function (image) {    // for each link l in ArrayOfImages
        var img = document.createElement('img'); // create an img element
        img.src = image;                         // set its src to the link l
        img.height = '300';
        img.width = '200';
        img.hspace = '20';
        document.body.appendChild(img);          // append it to the body 
    });


        var addButton = document.getElementById('addLeader');
        addButton.addEventListener('click', addLeader);

    }

   function addLeader(){
    ArrayOfImages.push('images/kimjongun.jpg');
    console.log(ArrayOfImages);
   }


</script>

If you turn the display part into a function you can call it to re-render. I made a simple and naive version.

var ArrayOfImages = ['images/trump.jpg', 'images/putin.jpg', 'images/merkel.jpg', 'images/jinping.jpg'];  //array of images

function displayImages (images) {
    images.forEach(function (image) {    // for each link l in ArrayOfImages
        var img = document.createElement('img'); // create an img element
        img.src = image;                         // set its src to the link l
        img.height = '300';
        img.width = '200';
        img.hspace = '20';
        document.body.appendChild(img);          // append it to the body 
    });
}

var addButton = document.getElementById('addLeader');
addButton.addEventListener('click', addLeader);
displayImages(ArrayOfImages);

function addLeader(){
    ArrayOfImages.push('images/kimjongun.jpg');
    document.body.innerHTML = ''; //clear previous images
    displayImages(ArrayOfImages);
}

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