简体   繁体   English

如何从.txt文件中提取内容并在HTML中显示它的随机行?

[英]How do I pull contents from a .txt file and display a random line of it in HTML?

Being a noob at HTML, I only know a solution to this in C#. 作为HTML的菜鸟,我只知道C#的解决方案。 I'm just trying to separate each line of the .txt so I can randomly pull lines from it and display them when a button is pressed. 我只是试图将.txt的每一行分开,所以我可以从中随机提取各行并在按下按钮时显示它们。 In addition, rather than using a submit button, I wanted to create a div of my own styled button for the user to press. 另外,我不想使用提交按钮,而是想创建我自己的样式按钮的div供用户按下。 (Which I know how to do) and use a jQuery 'on click'. (我知道该怎么做)并使用jQuery“单击”。

I'm a little unsure how to describe exactly what I'm trying to do, but I hope I did it well enough. 我不太确定如何准确描述我要做什么,但是我希望我做得足够好。

Thank you guys in advance. 预先谢谢你们。

Note This is the C# I used to create a relatively simple Trivia game. 注意这是我用来创建相对简单的Trivia游戏的C#。 In a separate Trivia.cs I had split the question and answers from each other (In the .txt they were separated by an *) 在单独的Trivia.cs中,我将问题和答案彼此分开(在.txt中,它们之间用*分隔)

I'm not sure if this will help guide anyone, however. 我不确定这是否可以帮助任何人。

static List GetTriviaList() { //Get Contents from the file. 静态列表GetTriviaList(){//从文件中获取内容。 Remove the special char "\\r". 删除特殊字符“ \\ r”。 Split on each line. 在每一行上拆分。 Convert to a list. 转换为列表。 List contents = File.ReadAllText("trivia.txt").Replace("\\r", "").Split('\\n').ToList(); 列表内容= File.ReadAllText(“ trivia.txt”)。Replace(“ \\ r”,“”).Split('\\ n')。ToList();

        //Each item in list "contents" is now one line of the Trivia.txt document.

        //make a new list to return all trivia questions
        List<Trivia> returnList = new List<Trivia>();
        // TODO: go through each line in contents of the trivia file and make a trivia object.
        //       add it to our return list.
        // Example: Trivia newTrivia = new Trivia("what is my name?*question");
        //Return the full list of trivia questions
        foreach (var item in contents)
        {
            Trivia bestTrivia = new Trivia(item);
            returnList.Add(bestTrivia);
        }

        return returnList;
    }

Here's a working Plunker showing how you could do it with just JavaScript (using the jQuery library). 这是一个工作的Plunker,显示了如何仅使用JavaScript(使用jQuery库)即可做到这一点。

http://plnkr.co/edit/BUCZOKd0MFDsa2jdMkJs?p=preview http://plnkr.co/edit/BUCZOKd0MFDsa2jdMkJs?p=preview

The basic process is as follows: 基本过程如下:

  1. Fetch the text file from the server 从服务器获取文本文件
  2. Split it into an array of lines 将其拆分为行数组
  3. When the user clicks the button, generate a random number 当用户单击按钮时,生成一个随机数
  4. Display the line corresponding to the random number 显示对应于随机数的行

Here's the JavaScript for that (see the Plunker above for full source): 这是用于此的JavaScript(有关完整源代码,请参见上面的Plunker):

var lines;
var randomNumber;
var lastRandomNumber;

$(document.body).ready(function () {

  // load the trivia from the server
  $.ajax({
    url: 'trivia.txt'
  }).done(function(content) {

    // normalize the line breaks, then split into lines
    lines = content.replace(/\r\n|\r/g, '\n').trim().split('\n');

    // only set up the click handler if there were lines found
    if (lines && lines.length) {
      $('#showLine').on('click', function () {
        // loop to prevent repeating the last random number
        while (randomNumber === lastRandomNumber) {
          randomNumber = parseInt(Math.random() * lines.length);
          // check to prevent infinite loop
          if (lines.length === 1) { break; }
        }
        // keep track of the last random number
        lastRandomNumber = randomNumber;

        // show the corresponding line
        $('#trivia').text(lines[randomNumber]);
      });
    }
  });
});

UPDATE: Added some explanatory comments to the JavaScript (updated above and in the Plunker). 更新:在JavaScript中添加了一些解释性注释(已在Plunker中和上方更新)。 Also added a check to prevent getting the same random line twice in a row. 还添加了一项检查,以防止连续两次获得相同的随机行。

I strongly suggest you to use server-side language, like PHP. 我强烈建议您使用服务器端语言,例如PHP。 Otherwise you will not be able to read only one word or string from the file. 否则,您将只能从文件中读取一个单词或字符串。 The javascript works in browser and to parse a file, as a first step, it would need the file fully loaded into the browser. javascript可在浏览器中工作并解析文件,作为第一步,它需要将文件完全加载到浏览器中。

PS PS

Based on the task I would not recommend you to use JQuery or Javascript. 根据任务,我不建议您使用JQuery或Javascript。 Most likely this task would mean a protection, as in early years, this way was used to activate a copy of purchased software. 这项工作很可能意味着一种保护,因为在早期,这种方法被用来激活购买的软件的副本。 Presumably, the soft was bought with instruction and the activation algorithm demand word from instruction pointing page number, row number and number of the word in a row. 大概是用指令购买了软件,并且激活算法从指令指向的页号,行号和连续字的编号中要求字。 In the case of Javascript - all this mechanism would be working on client site. 对于Javascript,所有这些机制都可以在客户端站点上使用。 It would need to load the file fully and parse it in browser where every one would debug it and extract the secret text fully. 它需要完全加载文件并在浏览器中解析它,每个人都将对其进行调试并完全提取秘密文本。 It would be an easy to crack protection. 这很容易破解。

暂无
暂无

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

相关问题 从 .txt 文件中取出一行并显示在 html 页面中 - Take line from .txt file and display in html page HTML-如何将 .txt 文件的内容插入到变量中以使用 .innerHTML 更改其内容? - HTML- How can I insert the contents of a .txt file into a variable to use .innerHTML to change the contents of <body>? 如何在Web浏览器中读取.txt文件的内容,对其进行修改并将其显示为html页面? - How to read the contents of a .txt file, modify it, and display it as an html page on local host in web browser? 动态加载时,如何从 a.txt 文件中获取动态内容以显示在多个 html 页面中 - How can I get dynamic content from a .txt file to display in multiple html pages when they are loaded dynamically 如何显示/隐藏来自PHP文件的html消息 - How do I display/hide an html message from a PHP file 如何使用带有 jsonp 的异步 function 在 a.txt 文件中显示文本? - How do I display text in a .txt file with an async function with jsonp? 如何使用 .txt 文件并将每一行作为数组读取? - How do I use a .txt file and read each line as an array? 如何在网页中显示从服务器(使用ajax和jquery)检索到的js文件的内容? - How do I display the contents of js file retrieved from the server (using ajax and jquery) in my webpage? 将 .txt 文件中的文本拉入<input>值 HTML - Pull text from a .txt file into <input> value HTML 如何在javascript中显示多个行文件内容 - how to display multiple line file contents in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM