[英]jQuery get a random line from text file
I have a .txt file, with around 754 lines. 我有一个.txt文件,大约有754行。 Each line has a pattern like this:
每行都有这样的模式:
1st part text#2nd part text#3rd part text or number
第一部分文字#2第二部分文字#3第三部分文字或数字
The hashtag is the delimiter! 标签是定界符!
What I'm trying to do is to get() or read() this text file, and retrieve a random line from it, with all the pattern. 我想做的是获取()或读取()此文本文件,并从其中检索所有模式的随机行。 But it has to be a random line.
但这必须是一条随机线。 So I can print it or append html to a div.
所以我可以打印它或将html附加到div。 It should look something like this:
它看起来应该像这样:
It has this pattern, because maybe I'll have to retrieve only one part of the pattern. 它具有这种模式,因为也许我只需要检索模式的一部分。
I don't know if a text file is the right type of file to pull data from.... But its only 80kb. 我不知道文本文件是否是从中提取数据的文件的正确类型。但是它只有80kb。 There is any way to do this?
有什么办法吗? Could someone give me a hand?
有人可以帮我吗? I'm actually a designer, this thing is driving me crazy.
我实际上是一名设计师,这件事使我发疯。
What I got... Trying to count how many lines the txt have, so I can get a random line. 我得到了什么...试图计算txt的行数,以便获得随机行。 It doesn't work.
没用 Does the text file must have \\n on the end of each line?
文本文件的每行末尾是否必须带有\\ n?
$.get('txt/messages.txt', function(txt) {
var lines = txt.responseText.split("\n");
for (var i = 0, len = lines.length; i < len; i++) {
save(lines[i]);
}
});
I'm using jQuery 1.11.1, and jQuery mobile 1.4.4 我正在使用jQuery 1.11.1和jQuery mobile 1.4.4
This is example of how to pull out a random line from the txt response: 这是如何从txt响应中拉出随机行的示例:
$.get('txt/messages.txt', function(txt) {
var lines = txt.responseText.split("\n");
var randLineNum = Math.floor(Math.random() * lines.length);
save(lines[randLineNum]); // random line from the text file
});
From there you can split that line based on the delimeter ( #
): 从那里,您可以根据分度符(
#
)分割该行:
lines[randLineNum].split("#");
Here's a jsfiddle example. 这是一个jsfiddle示例。 Hope this helps!
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.