等待jquery .html方法完成呈现 [英] Wait for jquery .html method to finish rendering

查看:89
本文介绍了等待jquery .html方法完成呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有垂直滚动条的div。 Div通过ajax动态更新,并且使用jQuery的.html方法插入html。
div更新后,滚动条返回顶端,我试图保持它在前面的位置。



这就是我想要的: / p>

  var scrollPos = $('div#some_id')。scrollTop(); //记住滚动pos 
$ .ajax({...
成功:函数(数据){
$('div#some_id')。html(data.html_content); //插入html内容
$('div#some_id')。scrollTop(scrollPos); // restore scroll pos
}
});

失败。我最好的猜测是,由于插入的html没有呈现(即没有滚动),所以它是失败的。



例如这可以工作。

  setTimeout(function(){
$('div#some_id')。scrollTop(scrollPos);
},200);

但在我看来这是肮脏的黑客攻击。我无法知道某些浏览器不会花费更多的时间来呈现插入的内容。



有没有办法等待浏览器完成渲染插入的html在继续之前呢?

解决方案

它仍然是一个黑客,当HTML被插入并准备就绪时,但您可以检查 html_content 中的元素是否每200毫秒插入一次以确保它们确实已准备就绪等。

从ajax调用中检查HTML中的最后一个元素:

  var timer = setInterval(function(){
if ($(#lastElementFromAjaxID).length){
$('div#some_id')。scrollTop(scrollPos);
clearInterval(timer);
}
}, 200);

对于更高级的选项,您可以在没有间隔的情况下做这样的事情,并将其绑定到DOMnodeInserted ,并检查是否插入了最后一个元素。


I have div with vertical scroll bar. Div is being updated dynamically via ajax and html is inserted using jQuery's .html method. After div is updated scroll bar returns to top and I am trying to keep it in the previous position.

This is how I'm trying it:

var scrollPos = $('div#some_id').scrollTop(); //remember scroll pos
$.ajax({...
    success: function(data) {
        $('div#some_id').html(data.html_content); //insert html content
        $('div#some_id').scrollTop(scrollPos); //restore scroll pos
    }
});

This fails. My best guess is that it is failing due to inserted html not rendered (ie. no scroll).

For example this works.

setTimeout(function(){
    $('div#some_id').scrollTop(scrollPos);
}, 200);

But this is dirty hack in my opinion. I have no way of knowing that some browsers won't take more then these 200ms to render inserted content.

Is there a way to wait for browser to finish rendering inserted html before continuing ?

解决方案

It's still a hack, and there really is no callback available for when the HTML is actually inserted and ready, but you could check if the elements in html_content is inserted every 200ms to make sure they really are ready etc.

Check the last element in the HTML from the ajax call:

var timer = setInterval(function(){
   if ($("#lastElementFromAjaxID").length) {
       $('div#some_id').scrollTop(scrollPos);
       clearInterval(timer);
   }
}, 200);

For a more advanced option you could probably do something like this without the interval, and bind it to DOMnodeInserted, and check if the last element is inserted.

这篇关于等待jquery .html方法完成呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆