簡體   English   中英

上傳文件和圖像顯示的簡單預覽不起作用

[英]Uploading file and simple previewing of the image display not working

我寫了一個小的 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

        }
    });
  });   

output(但它不適用於第二個按鈕)

問題是第二個按鈕沒有激活。 這是因為在這段代碼中(在加載時執行):

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

僅找到文件類型的輸入元素的第一個實例。 這就是 document.querySelector 所做的。

要確保找到這種類型的每個按鈕,以便您可以為其設置事件偵聽器,請查看使用 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