简体   繁体   English

上传文件和图像显示的简单预览不起作用

[英]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.我写了一个小的 function 选择图像并显示它的预览,但我无法弄清楚如何使它多次为不同的按钮工作。 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) output(但它不适用于第二个按钮)

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.这就是 document.querySelector 所做的。

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.要确保找到这种类型的每个按钮,以便您可以为其设置事件侦听器,请查看使用 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请参阅https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM