[英]Read text from a txt file using javascript and display in a bootstrap modal dialog (via knockout binding)
[英]To display text from a txt file using javascript
如何使用一个按钮浏览txt文件并使用另一个按钮显示文本来从txt文件读取文本。 请帮助我获取代码。 我已经尝试了许多代码,但是其他都可以。 一些代码是这样的。 提前致谢
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "@":
output=output.split("\n").filter(/./.test, /\@/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
您应该正确阅读如下文章: http : //www.html5rocks.com/en/tutorials/file/dndfiles/
不要以为这条线工作正常:
output=output.split("\n").filter(/./.test, /\@/).join("\n");
尝试将其更改为:
output=output.split("\n").filter(function(l) {
//return /^\@/.test(l); // Starting with @
return l.indexOf('@') > -1; // Containing @
}).join("\n");
看看这是否也将很有趣:
output=output.split("\n").filter(/\@/.test.bind(/\@/)).join("\n");
传递给.filter
方法的第二个参数是上下文:
array.filter(callback [,thisObject])
获取输入文件,使用FileReader()读取它,在文件加载时获取与模式匹配的文本。 最后通过“ main” div显示它。 应该管用..
HTML:
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery的:
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\@/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.