上传后显示图像预览

问题描述 投票:0回答:1

我有一个用于输入文件图像预览的js代码。当我选择图片时,两边都显示。如何分开?

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader()
    reader.onload = function(e) {
      $(".bruh").attr("src", e.target.result)
    }
    reader.readAsDataURL(input.files[0])
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="photo-select">
  <input type="file" onchange="readURL(this);" />
  <img class="bruh" src="" alt="" />
</label>

<label class="photo-select">
  <input type="file" onchange="readURL(this);" />
  <img class="bruh" src="" alt="" />
</label>
javascript jquery input imageview multiple
1个回答
0
投票

您可以用name分隔它们:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('.bruh'+input.name).attr('src', e.target.result);
    };
    reader.readAsDataURL(input.files[0]);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="photo-select">
  <input type='file' name="First" onchange="readURL(this);" />
  <img class="bruhFirst" src="" alt="" />
</label>
        
<label class="photo-select">
  <input type='file' name="Second" onchange="readURL(this);" />
  <img class="bruhSecond" src="" alt="" />
</label>
© www.soinside.com 2019 - 2024. All rights reserved.