javascript - jquery-function 不显示任何内容

标签 javascript jquery

我正在尝试创建一个随机生成器,如果在另一个页面上找到提示,则使用 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/

相关文章:

JavaScript 解析数组并获取唯一值

javascript - 没有模板引擎的 Node View 传递的数据

php - 如何从 wp 主题 wp_dequeue_script 或 wp_deregister_script jquery (不受影响)文件

jQuery 嵌套跨度文本值

javascript - pattern.test 不是函数

javascript调试进入VM****文件如何黑箱这些文件?

javascript - 使用正确的 header 和 OPTIONS 请求,仍然得到 "No Access-Control-Allow-Origin header is present on the requested resource"

javascript - JavaScript 中的键值对

jquery - 如何让我的特定菜单使事件元素具有不同的颜色

jquery - jquery 中的 "What Tag did I select?"