【问题标题】:jQuery Document Ready sometimes not executedjQuery Document Ready 有时不执行
【发布时间】:2020-01-02 22:07:58
【问题描述】:

我在 $(document).ready(function () {...}); 中遇到 jquery 代码问题,有时在页面加载时没有执行。

如何强制执行函数?或者如果与异步问题有关,则强制代码等待函数完成?

<!DOCTYPE html>
<html>
   <head>
      <link rel='icon' href='images/favicon.ico' type='image/x-icon'/ >
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script>
         var fileReading = new Array();
            $.get('output.txt', function(data){
                     fileReading = data.split(',');
                     fileReadingLength = fileReading.length-1;
            });
            $(document).ready(function () {
               $("#img1").attr({ "src": fileReading[fileReadingLength-1] });
               $("#img2").attr({ "src": fileReading[1] });
               $("fileReadingLength").text(fileReadingLength);
               for (i = 0; i <= fileReadingLength; i++) {
                  $('body').append('<br><img id="img"'+i+' src="'+fileReading[i]+'">')
               }
            });
      </script>
   </head>
   <body>
      Number of images: <fileReadingLength></fileReadingLength> <br>
   </body>
</html>

【问题讨论】:

  • 为什么不将文档中的 get 准备好,然后在 get 中运行文档中的代码,这样您就知道您拥有所需的变量 - jsfiddle.net/fh21dz9v
  • @Debendra 不,不是。它的存在是为了让您可以将代码放在文档中的任何位置。
  • 您提供的代码运行良好。在.ready 回调中添加一个console.log(),你会看到它确实在工作。
  • 可以放置在任何地方,但如果在文档末尾使用它会有性能优势。
  • @Debendra 如果您将脚本放在那里,则不需要准备好文档 - 准备好文档的重点是它可以放在任何地方,并且会等到文档准备好,如果您将它放在文档的结尾,然后它的 dom 无论如何都准备好了

标签: jquery html ajax


【解决方案1】:

我的理解是,由于您的 .get 是异步完成的,因此对于大文件,$(document).readyfileReading 具有元素之前触发。为什么不将$(document).ready 移动到.get 中,即使在文档准备好后设置它也保证会触发。

<html>
    <head>
    <link rel='icon' href='images/favicon.ico' type='image/x-icon'/ >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        var fileReading = new Array();
        $.get('output.txt', function(data){
            fileReading = data.split(',');
            fileReadingLength = fileReading.length-1;
            $(function () {
                $("#img1").attr({ "src": fileReading[fileReadingLength-1] });
                $("#img2").attr({ "src": fileReading[1] });
                $("fileReadingLength").text(fileReadingLength);
                for (i = 0; i <= fileReadingLength; i++) {
                    $('body').append('<br><img id="img"'+i+' src="'+fileReading[i]+'">')
                }
            });
        });
    </script>
    </head>
    <body>
    Number of images: <fileReadingLength></fileReadingLength> <br>
    </body>
</html>

注意:自 jQuery 3.0 起,$(document).ready(handler) 已被弃用,取而代之的是 $(handler)

【讨论】:

  • 由于模块化,这应该是公认的答案。
  • 这很完美!也感谢您的精彩解释。
【解决方案2】:

它有时不起作用的原因是因为$.get 是异步的。如果文档在 $.get 块返回响应之前准备好,那么您将没有 fileReadingfileReadingLength 的值。

因此,解决方案实际上是将所有 DOM 修改/更新逻辑抽象为一个函数,然后在解决 $.get 承诺后调用该函数:

$(document).ready(function() {
    function updateDom(fileReading) {
        var fileReadingLength = fileReading.length - 1;

        $("#img1").attr({ "src": fileReading[fileReadingLength - 1] });
        $("#img2").attr({ "src": fileReading[1] });

        $("fileReadingLength").text(fileReadingLength);

        for (i = 0; i <= fileReadingLength; i++) {
            $('body').append('<br><img id="img"'+i+' src="'+fileReading[i]+'">')
        }
    }

    $.get('output.txt', function(data) {
        updateDom(data.split(','));
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多