【问题标题】:HTML5 FileList and JQuery's eachHTML5 FileList 和 JQuery 的每个
【发布时间】:2011-07-15 21:00:40
【问题描述】:

我抓取文件列表 ([http://www.w3.org/TR/FileAPI/#dfn-filelist]),然后我想使用 JQuery 的 each 函数。

var file_list = $(this).attr('files');
/* Code goes here */
file_list.each(function()
{
/* Code goes here */

我收到以下错误:

Uncaught TypeError: Object #<FileList> has no method 'each'

有什么想法吗?谢谢。

【问题讨论】:

  • 你确定你的 file_list 是可迭代的吗?你能解释一下你的代码吗?

标签: javascript jquery file html each


【解决方案1】:

这是因为$(this).attr('files'); 只返回纯 DOM 文件列表,而不是 jQuery 对象。

要么你需要用老式的方式循环它:

for(var i=0,file;file=file_list[i];i++) {
 //do your thing
}

或者你可以使用 $.each:

$.each(file_list,function(idx,elm){
     //do your thing
});

请注意 $.each 比普通的 for 循环慢,在这种情况下给您带来的便利很少,所以我会坚持使用 for 循环。

【讨论】:

  • 如何获取 JQuery 对象?
  • @thom:你不知道 - 文件列表不是 DOM 元素而是 javascript 构造,jQuery 无法以有意义的方式包装它。这就像试图包装一个 regExp 对象。
  • file=file_list[i] 样式条件是否有名称?我总是看到i&lt;file_list.length,但对这种语法或它的优点/缺点感到困惑。
  • 我不知道该构造的名称,但如果您有一个正在遍历的对象数组,它是获取每个对象的便捷捷径。它之所以有效,是因为当您尝试访问超出范围的索引时,该构造将返回undefined,该索引将被强制转换为false,从而结束循环(对象始终被强制转换为true)。另一方面,如果数组可以保存将被强制为 false 的值,例如 0 或空字符串,则不应使用该构造
【解决方案2】:
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
});

【讨论】:

    【解决方案3】:

    2011 年 5 月,jQuery 1.6 发布,它改变了 .attr() 的行为,你应该使用 .prop() 而不是访问文件输入的 files 属性。
    这里有一些额外的方法来处理一个 FileList 对象。

    //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);});
    

    如果有人想做自己的研究:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 2020-06-25
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      相关资源
      最近更新 更多