jquery html()回调函数 [英] jquery html() callback function

查看:135
本文介绍了jquery html()回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经被问了几次,但没有以这样的方式回答,它可以帮助我解决我的具体问题。从导航列表中,单击一个项目,我使用 .html()函数将一些HTML内容加载到div中。没有ajax请求。 HTML内容包含图片。因此它可能需要一些时间来加载。由于 .html()是同步操作,所以下一行将立即执行。



只要我使用 .html()加载内容,我启用名为tinyscrollbar的第三方自定义滚动条。如果加载的内容有图像,那么滚动条会比加载图像的时间早一点计算内容div的高度,从而生成一个不会一直滚动的滚动条。



我不想使用 .setInterval()。有没有解决方案?在jQuery中是否有一些其他函数的功能类似于 .html()函数,但具有某种回调功能?


解决方案

基于Mike Robinson(和dystroy)的建议,我的问题的答案是:

  $(#myContentDiv)。html('HTML content comes here'); 
var contentImages = $(#myContentDiv img);
var totalImages = contentImages.length;
var loadedImages = 0;
contentImages.each(function(){
$(this).on('load',function(){
loadedImages ++;
if(loadedImages == totalImages)
{
$(#myContentDiv)。tinyscrollbar();
}
});
});


This question has been asked a couple times but not answered in such a way that it can help me with my specific issue. From a nav list, on click of an item, I'm loading some HTML content into a div using the .html() function. There is no ajax request. The HTML content has images. Hence it can take a moment to load up. And since .html() is a synchronous operation, the next line will immediately execute.

As soon as I load contents using .html(), I'm enabling a third party custom scrollbar called tinyscrollbar. If the loaded content had images, then the scrollbar calculates the height of the content div a little earlier than the images are loaded resulting into a scrollbar that won't scroll all the way.

I do not want to use .setInterval(). Is there a solution for this? Is there some other function in jQuery that acts like the .html() function but has some sort of callback feature?

Thank you.

解决方案

Based on Mike Robinson's (and dystroy's) suggestion the answer to my question is:

$("#myContentDiv").html('HTML content comes here');
var contentImages = $("#myContentDiv img");
    var totalImages = contentImages.length;
    var loadedImages = 0;
    contentImages.each(function(){
        $(this).on('load', function(){
            loadedImages++;
            if(loadedImages == totalImages)
            {
                $("#myContentDiv").tinyscrollbar();
            }
        });
    });

这篇关于jquery html()回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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