【问题标题】:Delay javascript execution until DOM changes complete延迟 javascript 执行,直到 DOM 更改完成
【发布时间】:2012-03-14 17:04:48
【问题描述】:

我需要暂停 javascript 的执行,直到 DOM 更改完成。我正在使用 jquery append 进行 DOM 更改,并使用附加图像的属性设置一些 post 变量。我已经查看了有关此的类似问题,但似乎与我想做的事情无关。代码如下:

var newImage = new Image();
newImage.src = *src is retrieved from previous variable*;
newImage.style.display = "none";
$('body').append(newImage);


var postData = {
    height: $('img:last')[0].height,
    width: $('img:last')[0].width
};

在某些情况下,追加会完成,我会得到正确的高度和宽度值,但大多数时候 DOM 还没有完成,我只是得到高度和宽度的 0。如何让 javascript 等待 DOM 完成其更改?我试过弄乱 jQuery .ready 但我似乎无法正确处理。

【问题讨论】:

    标签: javascript jquery dom settimeout delayed-execution


    【解决方案1】:

    您需要在newImage 对象上放置一个onload 处理程序,然后从该处理程序启动其余代码,例如:

    var newImage = new Image();
    newImage.style.display = "none";
    newImage.onload = function(ev) {
         // put the loaded image in the DOM
         $('body').append(this);
    
         // extract its properties
         var postData = {
            height: this.height,
            width: this.width
         }
    
         // do stuff with postData here
         // ...
    };
    newImage.src = *src is retrieved from previous variable*;
    

    【讨论】:

    • 我确实必须在 onload 中完成我以后的所有处理(包括到我的服务器的实际 POST)。但它奏效了。
    • @bjo 好吧,避免很长的回调函数的正常过程是将额外的东西分解到一个单独的函数中,然后从回调中调用 that 函数。
    【解决方案2】:

    在这种特定情况下,您似乎只想知道图像何时加载,然后在此时执行您的 javascript。您可以使用 onload 事件(纯 javascript)或 .load() (jQuery) 来做到这一点。

    var postData = {};
    var newImage = new Image();
    newImage.style.display = "none";
    newImage.onload = function() {
        postData.height = this.height;
        postData.width = this.width;
        // perhaps call some other function here that uses postData
    };
    newImage.src = *src is retrieved from previous variable*;
    $('body').append(newImage);
    

    必须在设置.src 值之前设置.onload 处理程序,否则在某些情况下您可能会错过加载事件。

    【讨论】:

    • 或 jQuery 1.7+ 中的 .on('load', ...)
    • 您对$(this).height() 的调用对隐藏元素不起作用。 OP 对.height 的使用是正确的。
    【解决方案3】:

    您可以在页面中运行您的代码,而不是使用当页面中的所有 html 都可用但未加载图像时触发的 jQuery 就绪事件

      $(window).load(function(){
           /* images now loaded ,run image based code*/
       })
    

    这将需要更长的时间才能触发,因此您可能会为与图像无关的元素/事件准备好运行的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 2016-02-24
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多