问题描述:
我有,我想用一个文件来拉,并检查每一行,看它是否大于240个字符一个JavaScript/HTML5页面解析的FileReader对象行:我现在有东西正确解析,但它们不能正确渲染。这里是我更新的代码:的javascript:</p> <p>编辑:如何通过线
<!DOCTYPE HTML>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<input type="file" id="input" name="file" multiple />
<br>
<output id="files"></output>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = function(e) {
// Print the contents of the file
var text = e.target.result;
var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks
for(var i = 0; i < lines.length; i++) {
if (lines[i].length > 240){
output.push('<li>' + lines[i] + '<br>');
}
}
};
reader.readAsText(f,"UTF-8");
}
document.getElementById('files').innerHTML = 'Paths with more than 240 characters: <br><ul>' + output.join('') + '</ul>';
}
document.getElementById('input').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
我可以运行跟踪,并查看该output
变量正确填充,但所有我得到的输出是:Paths with more than 240 characters:
没有output.join()
部分呈现正确 - 有什么想法?
答
我想你应该把
document.getElementById('files').innerHTML = 'Paths with more than 240 characters: <br><ul>' + output.join('') + '</ul>';
内onload
回调。当您尝试使用它时,似乎output
尚未填充。所以:
reader.onload = function (e) {
// all your code ...
// now can safely print output
document.getElementById('files').innerHTML = 'Paths with more than 240 characters: <br><ul>' + output.join('') + '</ul>';
};
答
显而易见的方法(如果你可以容忍一次读取文件)是通过换行来分割它。
var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks
for(var i = 0; i < lines.length; i++) { /* do something with lines[i] */ }
// or in modern JavaScript,
lines.forEach(function(line) { /* ... */ });
做到了!我想这是一个局部范围问题? – fox 2013-03-08 08:15:34
@fox否。读取文件内容是异步操作,所以当你尝试使用'output'时,它还没有被填充。 – dfsq 2013-03-08 08:30:31