简体   繁体   English

在 html 页面上使用 javascript 逐行读取和显示文件中的文本

[英]reading and displaying a text from a file line by line using javascript on html page

I am just learning javascript, so I need your help.我只是在学习 javascript,所以我需要你的帮助。 I have a text file, like following;我有一个文本文件,如下所示;

Text1
Text2
Text3
.....
.....
Textn

I would like to read all the content from the file line by line, so text by text, and display on html page one by one.我想逐行读取文件中的所有内容,因此逐个文本,并一一显示在 html 页面上。 One text will blink, disappear, and then next text will blink, disappear, etc. When it comes to the end, then it will start from the beginning of the file, and continue again line by line.一个文本会闪烁,消失,然后下一个文本会闪烁,消失,等等。当到达结尾时,它将从文件的开头开始,并逐行继续。

How can I do it?我该怎么做?

You can do it this way:你可以这样做:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example</title>
</head>

<body>
  <h1 id="my-element">Value</h1>

  <script>
    var target = document.getElementById("my-element");

    var content = null;
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "content.txt");
    xhr.onload = () => {
      content = xhr.response.split(/\r?\n/);
      let counter = 0;
      setInterval(() => {
        target.innerHTML = content[counter++ % content.length];
        setTimeout(() => target.innerHTML = "", 500);
      }, 1000);
    };
    xhr.send();

  </script>
</body>

</html>

But note that it doesn't work using file protocol and you should run a local server to use it.但请注意,它不适用于file协议,您应该运行本地服务器来使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM