簡體   English   中英

創建一個函數,單擊按鈕即可將圖像添加到數組

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

我有一個網頁,其中顯示了世界領導人的一系列圖像。

我需要添加一個按鈕,該按鈕將在該數組上添加一個額外的leader並顯示它。
如果有人能指出正確的方向,請先謝謝。

<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>

如果將顯示部件轉換為功能,則可以調用它以重新渲染。 我做了一個簡單而天真的版本。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM