2014-11-08 43 views
4

我传递的图像文件从XMLHttpRequest来此功能readfiles(文件)使用数据传递jQuery的功能的Onload停止循环,通过为环X内部功能

我想要做的是预览图像和图像文件名称,同时在reader.onload()函数内的一行代码中。

而且,因为将有超过1个文件传递给函数,我把它们扔到一个for循环

的问题是,当我试图通过预览图像readDataURL它确定,但文件名不能预览我认为,因为reader.onload()函数停止for循环通过图像文件循环。

这里是我的代码

function readfiles(files) { 

    var x; 

    for(x = 0; x < files.length; x = x + 1) { 

     var reader = new FileReader(); 
     reader.readAsDataURL(files[x]); 
     reader.onload = function(e) { 
      console.log(e.target.result); 
      console.log(files[x].name); 
     } 

    } 
} 

一直在寻找解决方案现在约5小时,任何帮助!

+1

你在控制台上得到什么? – dashtinejad 2014-11-08 03:41:41

+0

Uncaught TypeError:无法读取未定义的属性“名称” – 2014-11-08 03:44:15

回答

4

ROX的答案是不正确的。在他的情况下,你会看到它会输出4次相同的文件名。你需要的是一个闭包,它将在每次迭代时保持正确的上下文。您可以按如下所示完成此操作。检查小提琴http://jsfiddle.net/cy03fc8x/

function readfiles(files) { 
    for(x = 0; x < files.length; x = x + 1) { 
     var file = files[x]; 
     (function(file){ //this is a closure which we use to ensure each iteration has the right version of the variable 'file' 
      var reader = new FileReader(); 
      reader.readAsDataURL(file); 

      reader.onload = function(e) { 
       console.log(e.target.result); 
       console.log(file.name); 
      } 
     })(file);   //on each iteration, pass in the current file to the closure so that it can be used within 

    } 
} 
+0

它工作! ..我无法找到一种方式来感谢你,我真的很感激你的帮助..你救了我,非常感谢! – 2014-11-08 04:04:08

+2

是的,你是对的,在这里需要关闭,我也更新了我的答案,以保持它的正确性,也**'+ 1' ** :) – dashtinejad 2014-11-08 04:06:08

+0

我需要一个小小的mod,但它工作的很棒! – Deckard 2016-11-03 09:16:19

1

由于onload会稍后运行,此时x比您的文件数量多一个。例如,如果您有4个文件,执行onloadx将为5

所以参考保持到当前文件:

function readfiles(files) { 
    for (var x = 0; x < files.length; x = x + 1) { 
     // keep reference to current file on iteration 
     var file = files[x]; 

     // create closure and execute it 
     (function (file) { 
      var reader = new FileReader(); 
      reader.readAsDataURL(file); 

      reader.onload = function(e) { 
       console.log(file.name); 
      } 
     }(file)); // pass the `file` to the function 
    } 
} 
+1

我将变量名称保存在onload函数之外(复制并粘贴您的代码),结果给出了相同的文件名。 4次!像1.jpg | 1.jpg | 1.jpg ..等等!这是为什么发生? – 2014-11-08 03:54:53