jQuery在多个input.files上循环 [英] jQuery loop on multiple input.files
问题描述
我需要在多个文件输入上循环播放
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++;
});
在fileCount输出上的
alert()在选择多个文件时是1的0.没有进一步的警报.如果我用数字代替代码中的fileCount var,则它可以在适当位置工作. r.g. input.files [2] ...
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] ...
有什么主意吗?
推荐答案
执行以下操作:$("input[name='files[]']").each(function() {
您实际上正在获取与选择器匹配的任何元素.在这种情况下,您将获得单个多文件输入(这就是为什么您只看到1条警报的原因.您要做的是遍历文件.
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.
此页面上的代码几乎可以完全执行您想要的操作.我建议您检查一下:
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/
要将其应用于您的情况,您将执行以下操作:
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);
}
这篇关于jQuery在多个input.files上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!