【问题标题】:javascript: input a txt file to create an array and output its containt in htmljavascript: 输入一个文本文件来创建一个数组并以 html 输出它的内容
【发布时间】: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


    【解决方案1】:
    • )} 结尾有一些语法错误
    • 仅使用 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">
    

    【讨论】:

    • 好的,我可以看到它在 stackoverflow 提供的代码 sn-p 工具中做某事,它加载数组并显示一个值。我真正想念的是在应该使用的外部文件中工作。您真的是说我不必像 那样调用 中的函数?
    • 编辑了我的答案...如果您愿意,您仍然可以使用onchange="splitARRAY(event);" ,但是您必须按照我在选项 3 中向您展示的内容进行操作
    • 哦,顺便说一句,如果它适合你,那么做 innerText 比做 innerHTML 更安全
    • 是的,innerText 没问题。我知道事件监听器存在某种问题,实际上我无法使用选项 2 使该功能正常工作 - 但这不是新闻,总是有问题。我真正担心的是选项 3 都无法正常工作,基本上在脚本区域中调用了该函数,因为您建议从“var txtArr = []”粘贴以前的代码,但替换为“var file = event. target.files[0]" 在哪里使用 fileInput.files[0] 我的浏览器既没有给我一个错误页面。谢谢你的时间,但我没有成功
    • 我终于成功地正确使用了事件监听器,我可以确认您提供的解决方案是可以的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多