[英]Preview images to a loop html input with jquery in Asp.Net Core?
I have a loop in html that creates 4 inputs type of file and inside this loop I have an img tag to preview the selected image...我在 html 中有一个循环,它创建了 4 个输入类型的文件,在这个循环中我有一个 img 标签来预览所选图像...
<div class="gallery_imgproduct">
@for (int i = 0; i < 4; i++)
{
<div class="box_galleryimg col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="form-group">
<img id="main_image_product" src="~/site/img/product/286289f713.jpg" />
<input type="file" asp-for="ProductImgName" onchange="readURL(this);" class="form-control">
</div>
</div>
}
</div>
The jQuery code below is for preview input only...下面的 jQuery 代码仅用于预览输入...
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#main_image_product')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
I want the preview to be displayed in the img tag if the image is selected... If this is possible, please help.如果选择了图像,我希望在 img 标签中显示预览...如果可能,请帮忙。 If not, please suggest a solution.
如果没有,请提出解决方案。 Thank you
谢谢
You have preview image id as "main_image_product" inside for loop.您在 for 循环中将预览图像 ID 设为“main_image_product”。 The id must be unique.
id 必须是唯一的。 So you can take that image tag outside the loop or use $i to create unique ids for all preview images.
因此,您可以将该图像标记移出循环或使用 $i 为所有预览图像创建唯一 ID。
<img id="main_image_product" src="~/site/img/product/286289f713.jpg" />
<div class="gallery_imgproduct">
@for (int i = 0; i < 4; i++)
{
<div class="box_galleryimg col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="form-group">
<input type="file" asp-for="ProductImgName" onchange="readURL(this);" class="form-control">
</div>
</div>
}
</div>
OR或者
<div class="gallery_imgproduct">
@for (int i = 0; i < 4; i++)
{
<div class="box_galleryimg col-lg-3 col-md-3 col-sm-6 col-xs-12">
<div class="form-group">
<img id="main_image_product$i" src="~/site/img/product/286289f713.jpg" />
<input type="file" asp-for="ProductImgName" onchange="readURL(this,'main_image_product$i');" class="form-control">
</div>
</div>
}
</div>
function readURL(input,imgId) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#'+imgId)
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.