Javascript 使用数据API访问正在加载的图像的位置值

Javascript 使用数据API访问正在加载的图像的位置值,javascript,php,variables,bootstrap-4,Javascript,Php,Variables,Bootstrap 4,也许这是另一个愚蠢的问题,但它让我发疯。 基本上,我有这个表单来输入20个图像(由for生成) […]$('#拇指输出$i')。附加(img)[…] 谢谢。您可以使用.data()api获取ID号,为此,请在下面的一行中添加一个属性,例如索引 echo '<input type="file" data-index="'.$i.'" name="field'.$i.'" class="custom-file-input" id="inputGroupFile'.$i.'" aria-desc

也许这是另一个愚蠢的问题,但它让我发疯。 基本上,我有这个表单来输入20个图像(由for生成)

[…]$('#拇指输出$i')。附加(img)[…]


谢谢。

您可以使用
.data()
api获取ID号,为此,请在下面的一行中添加一个属性,例如索引

echo '<input type="file" data-index="'.$i.'" name="field'.$i.'" class="custom-file-input" id="inputGroupFile'.$i.'" aria-describedby="inputGroupFileAddon'.$i.'">';

为什么不将该处理程序附加到类
。自定义文件输入
,而不是使其特定于ID(如
#inputGroupFile3
)非常感谢,您让我的大脑免于崩溃:)
$(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
        }
    });
});
 $(document).ready(function(){
   $('#inputGroupFile<b>$i</b>').on('change' [...]
echo '<input type="file" data-index="'.$i.'" name="field'.$i.'" class="custom-file-input" id="inputGroupFile'.$i.'" aria-describedby="inputGroupFileAddon'.$i.'">';
$('.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