javascript 多个 input.files 上的 jQuery 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15821402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:13:18  来源:igfitidea点击:

jQuery loop on multiple input.files

javascriptjquery

提问by Tom

I need to loop this on a multiple file input:

我需要在多文件输入上循环这个:

    var reader = new FileReader();

    reader.onload = function (e) {
        $('#pprev_0')
        .attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);

I tried this, but it does not work:

我试过这个,但它不起作用:

var fileCount = 0;
$("input[name='files[]']").each(function() {

    var reader = new FileReader();

    reader.onload = function (e) {
        $('#pprev_'+fileCount)
        .attr('src', e.target.result)
        .css("display","block");
    };

    reader.readAsDataURL(input.files[fileCount]);

    fileCount++;
});

alert() on fileCount output is a one time 0 on multiple file selection. no further alerts. If I take numbers instead of the fileCount var in code, it works at position. r.g. input.files[2] ...

fileCount 输出上的 alert() 在多个文件选择上是一次 0。没有进一步的警报。如果我在代码中使用数字而不是 fileCount 变量,它会在位置上工作。rg input.files[2] ...

Any idea?

任何的想法?

回答by Simon C

When you do this: $("input[name='files[]']").each(function() {you are actually getting any elements that match the selector. In this case, you get your single multi file input (which is why you only see 1 alert. What you want to do is iterate over the files.

当您这样做时:$("input[name='files[]']").each(function() {您实际上获得了与选择器匹配的任何元素。在这种情况下,您将获得单个多文件输入(这就是您只看到 1 个警报的原因。您想要做的是遍历文件。

This page has code to do pretty much exactly what you want. I recommend you check it out:

该页面的代码几乎可以完全满足您的需求。我建议你检查一下:

http://www.html5rocks.com/en/tutorials/file/dndfiles/

http://www.html5rocks.com/en/tutorials/file/dndfiles/

To apply it to your situation, you would do something like this:

要将其应用于您的情况,您可以执行以下操作:

var files = $('#files')[0].files; //where files would be the id of your multi file input
//or use document.getElementById('files').files;

for (var i = 0, f; f = files[i]; i++) {

    var reader = new FileReader();

    reader.onload = function (e) {
        $('#pprev_'+fileCount)
        .attr('src', e.target.result)
        .css("display","block");
    };

    reader.readAsDataURL(f);

}