[英]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.