我正在尝试创建一个随机生成器,如果在另一个页面上找到提示,则使用 jQuery 会很容易,所以我尝试了以下操作。
<html>
<head>
<title>hello</title>
</head>
<body>
<script type="text/javascript">
$ (document).ready(function() {
$("body").load("hello.txt", function(msg) {
var textArray = msg.split("\n");
var zufall = Math.round ( ( textArray.length - 1 ) * ( Math.random() ) );
});
});
document.write('<p>' + textArray[zufall] + '</p>');
</script>
</body>
</html>
它应该像这样工作: 它加载一个包含多行文本的文档,并在换行符处将其拆分。这应该存储在一个数组中,并且随机行应该显示在网站上。
我的第一个想法是将文本直接写入数组,但我认为加载它对于网站来说会更有效。
感谢您的回答
PS:浏览器运行时不会出现“此页面错误”之类的错误信息。
最终编辑:
感谢您的帮助! 现在可以了。
解决方案如下:
<html>
<head>
<title>hello</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$ (document).ready(function() {
$.get("hello.txt", function(msg) {
var textArray = msg.split("\n");
var zufall = Math.round ( ( textArray.length - 1 ) * ( Math.random() ) );
$('body').append('<p>' + textArray[zufall] + '</p>');
});
});
</script>
</body>
</html>
最佳答案
您需要输入 document.write()
在你的function(msg)
里面因为 AJAX 是异步的并且 load
正在使用 AJAX,所以document.write()
不等到load
已完成调用匿名函数
$(document).ready(function() {
$.get("hello.txt", function(msg) {
var textArray = msg.split("\n");
var zufall = Math.round ( ( textArray.length - 1 ) * ( Math.random() ) );
$('body').append('<p>' + textArray[zufall] + '</p>');
});
});
编辑:
我刚刚注意到您没有包含 jquery 库 o_O
在您的 <script>
上方添加以下内容
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
关于javascript - jquery-function 不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10026518/