简体   繁体   English

FileReader如何获取ID

[英]filereader how to get id

I have this script: 我有这个脚本:

$.each($(this)[0].files, function(i, file){
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#display_image').prepend("<img src='"+e.target.result+"' />");
            };
            reader.readAsDataURL(input.files[count]);
        }
        count++;

});

so what it does is is simply gets all selected files path from multiple input and appends it to img tag. 所以它要做的就是简单地从multiple input获取所有选定文件的路径,并将其附加到img标签。

Now what i would like to do is give that img id which would be equals to variable count but my problem is that prepending function runs after my main each loop is finished so i always get the same number, like 3, 3, 3 not 1, 2, 3 i guess it's happening because of reader.onload , but i'm not sure how to do it differently... 现在我想要做的就是给那个IMG id这将是等于变量count ,但我的问题是,在前面加上功能我的主要运行后each循环结束,所以我总是得到相同的数字,比如3, 3, 31, 2, 3我想这是由于reader.onload而发生的,但是我不确定如何做不同的事情...

Post some more code and I can update and correct the below. 发布更多代码,我可以更新和更正以下内容。 But I think you want to use i . 但我认为您想使用i

$.each(
   $(this)[0].files, 
   function(i, file){
      if (input.files && input.files[0]) {
         var reader = new FileReader();
         reader.onload = function (e) {
            $('#display_image')
               .prepend("<img id='" i + 
                  "' src='"+e.target.result+"' />"
               );
          };
          reader.readAsDataURL(input.files[i]);
    }

});

Simples: 简单:

    img_id = 0;
$.each($(this)[0].files, function(i, file){
        if (input.files && input.files[0]) {
++img_id;
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#display_image').prepend("<img id='"+img_id+"' src='"+e.target.result+"' />");
            };
            reader.readAsDataURL(input.files[count]);
        }
        count++;

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM