在完全加载时将事件分配给div [英] assign event to div when it has loaded fully

查看:104
本文介绍了在完全加载时将事件分配给div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当包含div的所有元素都已完全加载时,我可以将事件分配给div来触发吗?例如。如果div包含图像,则在图像完全加载时在div上触发事件。我正在使用jquery。

Can I assign an event to a div to fire when all elements of the containing div have loaded fully? eg. if the div contains an image, fire an event on the div when the image has loaded fully. I am using jquery.

推荐答案

不确定如何动态添加内容,但这个例子应该说明它是如何工作的。

Not sure how you're dynamically adding your content, but this example should illustrate how it could work.

使用 .append()来模拟动态加载的内容。然后在追加之后,它使用 .find()来查找图像,并使用 .load()来附加一个加载处理程序。

It is using .append() to simulate your dynamically loaded content. Then after the append, it uses .find() to find the images, and .load() to attach a load handler to them.

最后,它返回图像的 length 属性。然后在加载处理程序中,当图像完成加载时,长度递减。一旦到达 0 ,所有图像都会被加载, if()中的代码会运行。

Finally, it returns the length property of the images. Then in the load handler, as the images finish loading, the length is decremented. Once it gets to 0, all the images are loaded, and the code inside the if() runs.

示例: http:// jsfiddle。 net / ehwyF /

var len = $('#mydiv').append('<img src = "http://dummyimage.com/150x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/160x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/170x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/180x90/f00/fff.png&text=my+image" />')
    .find('img')
    .load(function() {
        if( --len === 0) {
            alert('all are loaded');
        }
    }).length;

这样,代码只根据中的图像运行#mydiv

如果那里的图像不是动态的,因此不应该得到 .load( )事件,您应该能够添加 .not()过滤器以排除完成属性是 true

If there are any images in there that were not dynamic, and therefore shouldn't get the .load() event, you should be able to add a .not() filter to exclude ones the complete property is true.

将此位置放在 .find()<之后/ code>在 .load()之前。

.not(function(){return this.complete})

这篇关于在完全加载时将事件分配给div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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