jQuery.html(something)检测注入何时完成

jQuery.html( something ) detect when injection is complete

本文关键字:注入 何时完 检测 html something jQuery      更新时间:2023-09-26

简而言之,我希望在注入html并呈现该html的内容后触发回调。原因是我需要马上知道新内容的高度。类似这样的东西:

  $('div').html(tonsofstuff);
  console.log( $('div').height() ); //works in Firefox, but returns 0 in Chrome
  setTimeout(function(){
        console.log( $('div').height() ); //works everywhere, but takes too long
  },3000);

这个问题偶尔会出现在一些浏览器中(并且总是在chrome中)$('div').height()在新内容有高度之前触发。

我的幻想:

  $('div').html(tonsofstuff, function(){
        console.log( $('div').height() );
  });
  or even
  $('div').html(tonsofstuff).load(function(){
        console.log( $('div').height() );
  });

这就是我所做的:

var height = $('div').html(tonsofstuff).height();

我在等待它出现时从未遇到过任何问题。

如果您的"tonsofstuff"有图像,则setTimeout攻击是错误的方法。您需要知道每个图像何时加载,然后进行DOM高度计算。为此,你可能需要内省html来加载,找到图像,并使用对一些东西的调用,比如图像预加载插件。我不一定推荐它;编写自己的方法是相当琐碎的(尽管某些方法可能存在一些gotcha)。我只知道有这样的事情应该会很好地工作。

如果chrome中出现问题,我假设您插入的内容包含come图像。Chrome不会计算图像的尺寸,直到它们被完全加载(DOM就绪是不够的)。因此,通常可以解决问题的是在window.onload事件上执行渲染。这样可以确保加载的图像和.height()/.width()正常工作。尽管我意识到这并不总是可能的,因为window.onload事件是在DOMContentLoaded之后很久才触发的。

另一种方法是通过相应图像标签的widthheight属性显式地指定图像维度。如果你知道图像的大小,这可以工作。在这种情况下,没有必要在window.onload上执行您的逻辑。