在javascript中从本地文本文件中选取一个随机行

时间:2018-04-25 00:25:30

标签: javascript html

我有一个程序应该从本地文本文件中选择一个随机行,但它似乎无法正常工作。 这是代码:

<html>
<head>
    <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
    <h1 id = "gen">Alt Info: </h1>
    <script>
    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    var split = allText.split('\n')
                    var randomNum = Math.floor(Math.random() * split.length);
                    var randomLine = split[randomNum]
                    console.log("All Lines\n"+allText)
                    console.log("Line Numebr\n"+(randomNum+1))
                    console.log("Random Line\n"+randomLine)
                }
            }
        }
        rawFile.send(null);
    }
    readTextFile("alts.txt");
    </script>
    <button type="button" class=button onclick=document.getElementById("gen").innerHTML = randomLine;>Generate</button>

上面的代码应该从'alts.txt'文本文件中选择一个随机行,然后当点击生成按钮时,它应该在屏幕上显示该随机行。相反,当我点击生成按钮时,没有任何反应。如果有人可以帮助我那将是非常棒的!

1 个答案:

答案 0 :(得分:1)

您的button正在使用内联处理程序尝试引用不在全局范围内的变量。

内联事件处理程序在HTML标记中基本上是eval - 它们是不好的做法,导致代码很差,难以管理的代码。请认真考虑使用JavaScript附加您的活动,例如:https://developer.mozilla.org/en/DOM/element.addEventListener

另一个问题是#showText不存在 - 只需从脚本中删除该行。

这里有几个选项。一种是使randomLine成为一个全局变量,以便按需按钮引用它 - 这是不推荐的:

<script>
var randomLine;
function readTextFile(file)
  // ...
    var randomNum = Math.floor(Math.random() * split.length);
    randomLine = split[randomNum]

但除此之外,最好删除内联处理程序,并在按钮中正确添加单击侦听器:

document.querySelector('button').addEventListener('click', () => {
  document.getElementById('gen').textContent = randomLine;
});

或者,更好的是,根本不创建全局变量;保持只在需要的地方定义行,这是在听众内部:

(() => {
  var randomLine;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "alts.txt", false);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      if (rawFile.status === 200) {
        var allText = rawFile.responseText;
        var split = allText.split('\n')
        var randomNum = Math.floor(Math.random() * split.length);
        randomLine = split[randomNum]
        console.log("All Lines\n" + allText)
        console.log("Line Numebr\n" + (randomNum + 1))
        console.log("Random Line\n" + randomLine)
      }
    }
  }
  rawFile.send(null);

  const gen = document.getElementById('gen');
  document.querySelector('button').addEventListener('click', () => {
    if (randomLine) gen.textContent = randomLine;
    else gen.textContent = 'Not retrieved yet';
  });
})();

(或使用fetch和Promises代替处理异步性)