[英]How do I pull contents from a .txt file and display a random line of it in HTML?
作为HTML的菜鸟,我只知道C#的解决方案。 我只是试图将.txt的每一行分开,所以我可以从中随机提取各行并在按下按钮时显示它们。 另外,我不想使用提交按钮,而是想创建我自己的样式按钮的div供用户按下。 (我知道该怎么做)并使用jQuery“单击”。
我不太确定如何准确描述我要做什么,但是我希望我做得足够好。
预先谢谢你们。
注意这是我用来创建相对简单的Trivia游戏的C#。 在单独的Trivia.cs中,我将问题和答案彼此分开(在.txt中,它们之间用*分隔)
我不确定这是否可以帮助任何人。
静态列表GetTriviaList(){//从文件中获取内容。 删除特殊字符“ \\ r”。 在每一行上拆分。 转换为列表。 列表内容= 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;
}
这是一个工作的Plunker,显示了如何仅使用JavaScript(使用jQuery库)即可做到这一点。
http://plnkr.co/edit/BUCZOKd0MFDsa2jdMkJs?p=preview
基本过程如下:
这是用于此的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]);
});
}
});
});
更新:在JavaScript中添加了一些解释性注释(已在Plunker中和上方更新)。 还添加了一项检查,以防止连续两次获得相同的随机行。
我强烈建议您使用服务器端语言,例如PHP。 否则,您将只能从文件中读取一个单词或字符串。 javascript可在浏览器中工作并解析文件,作为第一步,它需要将文件完全加载到浏览器中。
PS
根据任务,我不建议您使用JQuery或Javascript。 这项工作很可能意味着一种保护,因为在早期,这种方法被用来激活购买的软件的副本。 大概是用指令购买了软件,并且激活算法从指令指向的页号,行号和连续字的编号中要求字。 对于Javascript,所有这些机制都可以在客户端站点上使用。 它需要完全加载文件并在浏览器中解析它,每个人都将对其进行调试并完全提取秘密文本。 这很容易破解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.