【问题标题】:Uploading file and simple previewing of the image display not working上传文件和图像显示的简单预览不起作用
【发布时间】:2021-06-29 20:52:16
【问题描述】:

我编写了一个小函数来选择图像并显示它的预览,但我无法弄清楚如何让它为不同的按钮多次工作。请帮帮我! 功能:

    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)

【问题讨论】:

    标签: javascript html css file upload


    【解决方案1】:

    问题是第二个按钮没有激活。那是因为在这段代码中(在加载时执行):

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

    仅找到文件类型的输入元素的第一个实例。这就是 document.querySelector 的作用。

    要确保找到此类型的每个按钮以便您可以为其设置事件监听器,请查看使用 document.querySelectorAll。这会返回一个节点集合,而不仅仅是一个节点,因此您需要单步执行此集合,为每个元素设置一个事件侦听器。

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

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 2012-06-13
      • 1970-01-01
      • 2021-09-28
      • 2019-07-28
      • 2012-10-05
      • 1970-01-01
      • 2012-09-26
      • 2017-04-03
      相关资源
      最近更新 更多