【发布时间】:2021-08-05 01:32:14
【问题描述】:
我试图从一个 txt 文件中读取数据,该文件可以从一个输入类型文件中选择,并在一个 html 内容中获取存储的信息,并通过数组传递它们。
已经有很多关于此的文章,但似乎没有人真正适合我的情况,但以下文章实际上来自How to read txt file and save it in array in javascript in html,它工作正常,但应该有点“标准化”以从函数调用。
所以现在正在尝试的是类似的东西(因为这不是真的有效):
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Read Text File</title>
<script>
function splitARRAY(){
var file = document.getElementById('myFile2');
file.addEventListener('change', () => { var txtArr = [];
var fr = new FileReader();
fr.onload = function() {
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
txtArr = [...txtArr, ...(lines[line].split(" "))];
}
fr.onloadend = function() {
console.log(txtArr);
document.getElementById('other').textContent=txtArr.join("");
document.getElementById("other2").innerHTML = txtArr[0];
document.getElementById("other3").innerHTML = txtArr[1];
document.getElementById("other4").innerHTML = txtArr[2];
document.getElementById("other5").innerHTML = txtArr[3];
console.log(txtArr[1]);
fr.readAsText(file.files[0]);
}
)
}
</script>
</head>
<body>
<input type="file" id="myFile2" onchange="splitARRAY();">
</br>
<span id="other">txt variable 1</span> </br>
<span id="other2">txt variable 2</span> <span id="other4">txt variable 4</span></br>
<span id="other3">txt variable 3</span> <span id="other5">txt variable 5</span></br>
</body>
</html>
肯定是做错了什么,因为这样我根本没有获得变量数据,但我真的看不出有什么问题。 顺便说一句,如果有人有更好的解决方案,我愿意尝试一下。
【问题讨论】:
标签: javascript arrays txt input-type-file