我有一个用于输入文件图像预览的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>
答案 0 :(得分:1)
您可以用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>