也许这是另一个愚蠢的问题,但它让我发疯。 基本上我有这个表格来输入 20 张图像(由 for 生成)
<?php
for ($i=0; $i<20; $i++)
{
echo '<div class="col-xl-4 col-lg-4 col-md-6">';
echo '<div class="file-field">';
echo '<div class="z-depth-1-half mb-4" id="thumb-output'.$i.'"></div>';
echo '<div class="d-flex justify-content-center">';
echo '<div class="custom-file">';
echo '<input type="file" name="field'.$i.'" class="custom-file-input" id="inputGroupFile'.$i.'" aria-describedby="inputGroupFileAddon'.$i.'">';
echo '<label class="custom-file-label" for="inputGroupFile'.$i.'">Choose file</label>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '';
echo '<div class="col-xl-8 col-lg-8 col-md-6">';
echo '</div>';
}
?>
我需要在上传之前显示一个缩略图,目前它只适用于其中一个字段(#inputGroupFile3 和#thumb-output3)。
$(document).ready(function(){
$('#inputGroupFile3').on('change', function(){ //on file input change
if (window.File && window.FileReader && window.FileList && window.Blob) //check File API supported browser
{
$('#thumb-output3').html(''); //clear html of output element
var data = $(this)[0].files; //this file data
$.each(data, function(index, file){ //loop though each file
if(/(\.|\/)(gif|jpe?g|png)$/i.test(file.type)){ //check supported file type
var fRead = new FileReader(); //new filereader
fRead.onload = (function(file){ //trigger function on successful read
return function(e) {
var img = $('<img/>').addClass('thumb img-fluid img-thumbnail').attr('src', e.target.result); //create image element
$('#thumb-output3').append(img); //append image to output element
};
})(file);
fRead.readAsDataURL(file); //URL representing the file's data.
}
});
}else{
alert("Your browser doesn't support File API!"); //if File API is absent
}
});
});
基本上我需要的是 PHP 代码中的东西 (id="thumb-output'.$i.')
但在 JS 中,类似于:
$(document).ready(function(){
$('#inputGroupFile<b>$i</b>').on('change' [...]
[...]$('#thumb-output<b>$i</b>').append(img)[...]
谢谢。
最佳答案
您可以使用 .data()
api 获取 ID 号,为此在下一行添加一个属性 index
echo '<input type="file" data-index="'.$i.'" name="field'.$i.'" class="custom-file-input" id="inputGroupFile'.$i.'" aria-describedby="inputGroupFileAddon'.$i.'">';
此属性将在您的 jQuery 事件处理程序中可用,您应该将其更改为通用的而不是特定于 ID 的。
$('.custom-file-input').on('change', function(){
//on file input change, (#inputGroupFile3 changed to .custom-file-input as
//it will listen to all images with that class).
var index = jQuery(this).data('index');
//this should now hold the index value of the current image like 1 or 2 or 3 so on,
///use the variable where ever you need the ID number.
//Rest of the handler body
关于javascript - 使用数据 API 访问正在加载的图像的位置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52621251/