how to loop this function?

2019-08-13 03:02发布

Thanks to some help on here I have a way of previewing images selected for and upload using:

<input type='file' name="files[]" onchange="readURL(this);" multiple />
<div id="previews"></div>

<script>
    function readURL(input) {
        if (input.files && input.files[0]) {

            var reader = new FileReader();

            reader.onload = function (e) {
                var container = $('#previews');
                var image = $('<img>').attr('src', e.target.result).width(150);
                image.appendTo(container);
            };
            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

I was wondering how to loop this function for each file selected on the input? I just don't see where to use something like .each()

edit:

am trying this.. but its wrong somewhere, as it displays 2 previews but both of the same image?

function readURL(input) {
    $.each(input.files,function(i) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var container = $('#previews');
            var image = $('<img>').attr('src', e.target.result).width(150);
            image.appendTo(container);
        };
        reader.readAsDataURL(input.files[0]);
    });
}

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-13 03:34

You just need to loop over the last line, where the file is selected.

function readURL(input) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var container = $('#previews');
        var image = $('<img>').attr('src', e.target.result).width(150);
        image.appendTo(container);
    };

    $.each(input.files,function(i) {
        reader.readAsDataURL(input.files[i]);
    });
}
查看更多
贼婆χ
3楼-- · 2019-08-13 03:49

input.files is a FileList, which acts like an array.
You can use jQuery.each on it like any other array.

查看更多
登录 后发表回答