简体   繁体   English

Javascript读取.txt文件并以HTML显示

[英]Javascript reading .txt file and displaying in HTML

I'm trying to have JavaScript on my HTML page read from a .txt file (status.txt) in the same directory and display the contents in two different font colors based on the information in the .txt file. 我正在尝试从同一目录中的.txt文件(status.txt)中读取HTML页面上的JavaScript,并根据.txt文件中的信息以两种不同的字体颜色显示内容。 I currently have it displaying the text on the page just fine, but I wanted to make it a bit more noticeable. 目前,我可以在页面上很好地显示文本,但是我想使其更加引人注目。 Here is my current code to display the text with the basic #ccc hex. 这是我当前的代码,以基本的#ccc十六进制显示文本。

<script type="text/javascript">
  loadXMLDoc();
</script>
<script type="text/javascript">
  function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("status").innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET", "status.txt", true);
    xmlhttp.send();
  }
</script>

<h3 id="status" style="padding-right: 7px; padding-left: 7px; margin-top: 2px; font-size: 11px; color: #cccccc">
  Status
</h3>

The text file contents are overwritten every time a .vbs file is ran. 每次运行.vbs文件时,文本文件内容都会被覆盖。 It will either say: 它会说:

6/11/2016 8:58:30 AM Script Started

or 要么

6/11/2016 9:31:12 AM Script Stopped

The only thing that changes is the timestamp. 唯一改变的是时间戳。 I would like the text to display as red when it says "(timestamp) Script Stopped" and green when it says "timestamp) Script Started". 我希望文本显示为“(timestamp)脚本已停止”时显示为红色,而显示为“ timestamp)脚本已开始时显示为绿色。 If anyone could help, that'd be great! 如果有人可以帮助,那就太好了!

You can use simple RegEx to add proper classes to your text. 您可以使用简单的RegEx向文本添加适当的类。

document.getElementById("status").innerHTML = xmlhttp.responseText
    .replace(/(\b\d.+?Started)/ig,'<span class="start">$1</span>')
    .replace(/(\b\d.+?Stopped)/ig,'<span class="stop">$1</span>');
    //\b -start of word, \d - any digit 0 to 9, . - any character
    // +? - one ore more, not greedy 
var color = xmlhttp.responseText.indexOf('Started') !== -1 ? 'green' : 'red';
document.getElementById("status").innerHTML = '<span style="color: ' + color + '">' + xmlhttp.responseText + '</span>';

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

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