簡體   English   中英

如何在多個輸入提示“文件”-s 中預覽圖像

[英]how to preview images in multiple input tipe "file"-s

我有這個代碼:

 const chosenImage = document.getElementById('chosen_image') for (const input of document.querySelectorAll('input[type=file]')) { input.onchange = (e) => { if (e.target.files.length) { let reader = new FileReader(); console.log(e.target.nextElementSibling); // do stuff reader.readAsDataURL(input.files[0]); reader.onload = () => { chosenImage.setAttribute("src", reader.result); e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, input.files[0].name) } } } }
 <div class="section_header"> <figure class="uploaded_image_container"> <img id="chosen_image"> </figure> <div class="upload_section_outer"> <h6>Text U:</h6> <div class="upload_section"> <button id="performance_img_20" onclick="document.getElementById('img_20').click()">Upload image</button> <input type="file" accept="image/png, image/jpg, image/svg" id='img_20' style="display:none"> <label>Upload complete: False</label> </div> </div> </div> <div class="section_header"> <figure class="uploaded_image_container"> <img id="chosen_image"> </figure> <div class="upload_section_outer"> <h6>Text U:</h6> <div class="upload_section"> <button id="performance_img_21" onclick="document.getElementById('img_21').click()">Upload image</button> <input type="file" accept="image/png, image/jpg, image/svg" id='img_21' style="display:none"> <label>Upload complete: False</label> </div> </div> </div> <div class="section_header"> <figure class="uploaded_image_container"> <img id="chosen_image"> </figure> <div class="upload_section_outer"> <h6>Text U:</h6> <div class="upload_section"> <button id="performance_img_19" onclick="document.getElementById('img_19').click()">Upload image</button> <input type="file" accept="image/png, image/jpg, image/svg" id='img_19' style="display:none"> <label>Upload complete: False</label> </div> </div> </div>

問題是它只在第一部分預覽,但我需要為每個上傳單獨顯示。 此外,文本僅針對第一個上傳的圖像發生變化,我不知道為什么。 誰能解釋我做錯了什么?

你在這里得到的是第一個 selected_image 元素,而不是第二個甚至第三個。

const chosenImage = document.getElementById('chosen_image'); 
//...
chosenImage.setAttribute("src", reader.result);
//...

推薦使用class,所以可以

const chosenImage = document.getElementsByClass('chosen_image')

let i = 0;
for (const input of document.querySelectorAll('input[type=file]')) {
  i++;
  input.onchange = (e) => {
    if (e.target.files.length) {
      let reader = new FileReader();
      console.log(e.target.nextElementSibling);
      // do stuff
      reader.readAsDataURL(input.files[0]);
      reader.onload = () => {
        chosenImage[i].setAttribute("src", reader.result); //edit here
        e.target.nextElementSibling.textContent = e.target.nextElementSibling.textContent.replace(/False/, input.files[0].name)
      }

    }
  }
}

暫無
暫無

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

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