javascript 加载 div 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12353554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onload for div tag
提问by Oto Shavadze
I have div tag, after some event, I insert (change old content) into this tag, several images and also texts, for example:
我有 div 标签,在一些事件之后,我将(更改旧内容)插入到这个标签中,几个图像和文本,例如:
$("#some_button").on("click", function () {
$("#mydiv").html("<div>aaaa</div><img src='1.jpg'><div>bbb</div><img src='2.jpg'>");
});
I want, that after load "mydiv" tag full content, alert("mydiv contonet is loaded"). That is, some like this:
我想要,在加载“mydiv”标签完整内容后,警报(“mydiv contonet 已加载”)。也就是说,有些像这样:
$("#mydiv").onload( function () {
alert("mydiv contonet is loaded");
});
Tell please, how can this make?
请告诉,这是怎么做到的?
回答by karim79
Divs have no onload event. The best you can do is something like this:
Div 没有 onload 事件。你能做的最好的事情是这样的:
<div id="myDiv">I am a div</div>
<script>// do stuff with loaded div</script>
...unless you can/want to specifically address stuff within the div which does support onload
, like images.
...除非您可以/想要专门解决支持 div 中的内容onload
,例如图像。
回答by Andrea Turri
.html()
is a synchronous operation. The actual updating of the DOM depends on what your html content is. If you have <img>
or <iframe>
tags, they will take time to load. The next statement following the .html()
should immediately see the new html contents.
.html()
是一个同步操作。DOM 的实际更新取决于您的 html 内容是什么。如果您有<img>
或<iframe>
标签,它们将需要时间来加载。后面的下一条语句.html()
应该立即看到新的 html 内容。
You can have a callback using .load()
您可以使用回调 .load()
回答by Lowkase
Preload (http://stackoverflow.com/questions/476679/preloading-images-with-jquery) your images then you won't have to worry about this use case.
预加载 (http://stackoverflow.com/questions/476679/preloading-images-with-jquery) 你的图片,那么你就不必担心这个用例了。
回答by Denys Séguret
You'll have to check the loading of the images you have in your div as there is no callback usable in your case.
您必须检查 div 中图像的加载情况,因为在您的情况下没有可用的回调。
The typical way is, for each image
典型的方式是,对于每个图像
- to check if the image is loaded (check
if (img.width)
) - add a onload callback on this image
- 检查图像是否已加载(检查
if (img.width)
) - 在此图像上添加一个 onload 回调
As you have multiple images, you might want a function like this one :
由于您有多个图像,您可能需要这样的功能:
function onLoadAll(images, callback) {
var n=0;
for (var i=images.length; i-->0;) {
if (images[i].width==0) {
n++;
images[i].onload=function(){
if (--n==0) callback();
};
}
}
if (n==0) callback();
}
that you can call like this :
你可以这样调用:
onLoadAll(imagesObj, function(){
// do something with imagesObj when all images are loaded
});