HTML5 FileList and JQuery's each
I grab the filelist ([http://www.w3.org/TR/FileAPI/#dfn-filelist]) and then I want to use JQuery's each function.
var file_list = $(this).attr('files');
/* Code goes here */
file_list.each(function()
{
/* Code goes here 开发者_运维技巧*/
I get the following error:
Uncaught TypeError: Object #<FileList> has no method 'each'
Any idea? Thank you.
It is because $(this).attr('files');
just returns the plain DOM file list, and not a jQuery object.
Either you need to loop over it the old fashioned way:
for(var i=0,file;file=file_list[i];i++) {
//do your thing
}
or you could use $.each:
$.each(file_list,function(idx,elm){
//do your thing
});
Be aware that $.each is slower than the plain for loop, and in this case gives you very little convenience, so i'd stick with the for loop.
var file_list = $(this).attr('files');
$.each(file_list,function(i,item){
// i is the index (integer) of current item
// item is the current item
// $(this) is the jQuery selector for the current item
});
In 2011 May, jQuery 1.6 was released which changed the behavior of .attr()
, you should use .prop()
instead to access the files
property of a file input.
Here are some additional ways to deal with a FileList object.
//Get the files property (FileList object) of a file input element from a jQuery instance.
var arraylike=$file_input.prop('files');
//Create an array from an arraylike object using the old hacky way
file_array=Array.prototype.splice.call(arraylike,0,0);
//Or the new way.
file_array=Array.from(arraylike);
//Or just work on it directly.
Array.prototype.forEach.call(arraylike,x=>{console.log(x);});
//Or if you really must use jQuery...
jQuery.each(arraylike,(k,v)=>{console.log(v);});
In case anyone wants to do their own research:
- jQuery 1.6 release
- $.fn.attr
- $.fn.prop
- $.each
- Array.prototype.slice
- Array.from
- Array.prototype.forEach
精彩评论