这个问题已被问过几次,但没有以这样的方式回答它可以帮助我解决我的具体问题。在导航列表中,点击某个项目后,我会使用.html()
功能将一些HTML内容加载到div中。没有ajax请求。 HTML内容包含图像。因此,加载可能需要一些时间。由于.html()
是同步操作,下一行将立即执行。
只要我使用.html()
加载内容,我就会启用名为tinyscrollbar的第三方自定义滚动条。如果加载的内容包含图像,则滚动条会比加载图像更早地计算内容div的高度,从而导致滚动条不会一直滚动。
我不想使用.setInterval()
。这有解决方案吗?在jQuery中是否有一些其他功能像.html()
函数一样但具有某种回调功能?
谢谢。
答案 0 :(得分:49)
$('#divId').html(someText).promise().done(function(){
//your callback logic / code here
});
答案 1 :(得分:7)
基于迈克罗宾逊(和破坏者)的建议,我的问题的答案是:
$("#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();
}
});
});
答案 2 :(得分:-3)
为了检查图像是否已加载,您可以使用以下内容;
<img src="your_image_path" />
<script>
$('img').load(function() {
//call_your_function();
});
</script>
答案 3 :(得分:-5)
$(window).load(function() {
// code here
})();