Using $(this) with FileReader() to target result

前端 未结 2 1034
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 15:44

I\'m trying to show an ajax preview of an image from a file input. Easy enough using FileReader() but I\'m using it with a loop so I when it\'s time to place the result inside a

2条回答
  •  耶瑟儿~
    2021-02-06 16:05

    This is how I would do it. Assign the target to the reader object itself and use it later.

    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            // set where you want to attach the preview
            reader.target_elem = $(input).parent().find('preview');
            reader.onload = function (e) {
               // Attach the preview
               $(reader.target_elem).attr('src', e.target.result);
            };
    
            reader.readAsDataURL(input.files[0]);
        }
     }
    

提交回复
热议问题