javascript:输入一个txt文件来创建一个数组,并用html输出它的containt



我试图从一个txt文件中读取数据,该文件可以从输入类型文件中选择,并通过数组将存储的信息传递到html内容中。

关于这一点,已经有很多文章了,但似乎没有人真正适合我的情况,但下面的文章——实际上来自于如何读取txt文件并将其保存在html中的javascript数组中,这很好,但应该有点"标准化",以便从函数中调用。

所以我现在尝试的是类似的东西(因为这并没有真正起作用(:

<!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> 

当然我做错了什么,因为用这种方式我根本没有获得变量数据,但我并没有真正看到哪里出了问题。顺便说一句,如果有人有更好的解决方案,我愿意尝试一下

  • )}最后出现了一些语法错误
  • 只使用fr.onload是足够的,但它永远不会被调用,因为你在里面调用readAsText
  • 您在监听更改事件时也有问题。当它第一次更改时,您调用splitARRAY函数,该函数每次更改时只会添加一个新的事件侦听器

无论如何,这里有一种更现代的方法,使用blobs 上的新读取方法

var fileInput = document.getElementById('myFile2');
fileInput.addEventListener('change', async () => {
var txtArr = []
var file = fileInput.files[0]
if (!file) return
var text = await file.text()
// By lines 
var lines = text.split('n')
for (var line = 0; line < lines.length; line++) {
txtArr = [...txtArr, ...(lines[line].split(" "))]
}
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])
})
<input type="file" id="myFile2" >
</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>

除了上面提供的方法之外,添加EventListener的其他方法可以是:

// opt: 2
var fileInput = document.getElementById('myFile2')
fileInput.onchange = async function (event) { ... }
// opt: 3
async function splitARRAY (event) { 
// don't add any extra EventListener in here
var txtArr = []
var file = event.target.files[0]
...
}
<input type="file" onchange="splitARRAY">

最新更新