我正在尝试使用FileReader()读取多个文件,然后对它们进行操作,但我无法弄清楚如何在onload循环之外使用文件数据。在这种情况下,我可以写入writer div,但只有“unidentified”输出到writer2 div。从我读过的,问题可能与关闭有关?我不确定。
<script type="text/javascript">
function Slurper(that)
{
if(that.files)
{
var allMaps=new Array();
for(i=0;i<that.files.length;i++)
{
var data = new FileReader()
data.readAsText(that.files[i]);
data.onload = function (event)
{
var input=event.target.result;
input=input.replace(/,/g," ");
input=input.replace(/\u0009/g," ");
input=input.replace(/(\r\n|\n|\r)/g," ");
input=input.replace(/ /g," ");
input=input.replace(/ /g," ");
allMaps[i]=input.split(" ");
allMaps[i].splice(0,19);
document.getElementById("writer").innerHTML+="<br>"+allMaps[i];
}
document.getElementById("writer2").innerHTML+="<br>"+allMaps[i];
}
}
}
答案 0 :(得分:0)
i
。所以i
将继续递增,当你的onload函数调用时i
将是你传入的文件数。我想你可能想要的是:
data.onload = function(index)
return (event)
{
var input=event.target.result;
input=input.replace(/,/g," ");
input=input.replace(/\u0009/g," ");
input=input.replace(/(\r\n|\n|\r)/g," ");
input=input.replace(/ /g," ");
input=input.replace(/ /g," ");
allMaps[index]=input.split(" ");
allMaps[index].splice(0,19);
document.getElementById("writer").innerHTML+="<br>"+allMaps[index];
}
}(i)
这会将i
的当前值绑定到您的回调函数。简而言之,是的,你应该阅读关闭和范围。