简体   繁体   中英

How to display .txt file content via Javascript and change style?

I created a tool that can automatically make some text passages bold. It should work like this: I have a .txt file where i want to insert my text that should be formatted. It is named hier.txt. I then display the content of the txt file via a Javascript on the site. Everything works until this point. I do have another Javascript that is supposed to then take the text and randomly make some passages of it appear in bold styling. When i previously tried to insert the text directly in the code, it worked, but it is important that it works with the text file since it is gonna be easier to use.

Here is the code of what I achieved so far:

Script to display the .txt:

$( document ).ready(function() {
  $('#randomText').load("hier.txt");
});

Other Script to make some words bold:

<script>

        target = document.getElementById("randomText");
oldHTML = target.innerHTML;

for (j=0; j<25;j++){
  words = oldHTML.split(" ");
  wordCount = words.length;
  var newHTML = "";
  var highlightStart = Math.floor(Math.random() * wordCount) + 1;
  var highlightLength = Math.floor(Math.random() * 5) + 1;
  for (i = 0; i < wordCount; i++) {
    if (i == highlightStart) newHTML = newHTML + "<b>";
    newHTML = newHTML + words[i] + " ";
    if (i == highlightStart + highlightLength) newHTML = newHTML +          "</b>";
    target.innerHTML = newHTML;
  }//for i
    oldHTML = newHTML;
}// for j

</script>

使用.load()回调函数在异步AJAX调用完成后执行任务

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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