简体   繁体   中英

Uploading file and simple previewing of the image display not working

I wrote a small function that picks a image and shows a preview of it but I am not able to figure out how to make it work multiple times for a different button similarly. Please help me out: The function:

    window.addEventListener('load', function() {
    document.querySelector('input[type="file"]').addEventListener('change', function() {
        if (this.files && this.files[0]) {
            var img = document.getElementById('img1');
            img.onload = () => {
                URL.revokeObjectURL(img.src);  // no longer needed, free memory
            }
  
            img.src = URL.createObjectURL(this.files[0]); // set src to blob url

        }
    });
  });   

the output (but it does not work for the second button)

The problem is that the second button is not active. That is because in this code (which is executed on load):

document.querySelector('input[type="file"]').addEventListener('change', function() {

only the first instance of an input element of type file is found. That is what document.querySelector does.

To make sure that every button of this type is found so you can set up an eventlistener for it, look at using document.querySelectorAll. This returns a collection of nodes, not just one, so you need to step through this collection, setting an event listener for each of the elements.

See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

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