我正在通过ajax加载一些html,我需要一个事件来捕捉新图像加载时...
因为它在div而不是整页,我不能使用 $(window).load(....
我尝试了以下但它不起作用:
$('.banners_col img:last').load(function(){.....
Run Code Online (Sandbox Code Playgroud)
在将它们插入dom之前,您需要定位ajax调用的结果.
因此,您需要使用jQuery提供的回调方法.
$('#load').click(function(){
// inside the handler that calls the ajax
//you ajax call here
$.get('the_url_to_fetch',function(data){
// create an in-memory DOM element, and insert the ajax results
var $live = $('<div>').html(data);
// apply a load method to the images in the ajax results
$('img',$live).load(function(){
// what to do for each image that is loaded
});
// add the ajax results in the DOM
$('selector_where_to_put_the_response').html($live.children());
});
});
Run Code Online (Sandbox Code Playgroud)
http://www.jsfiddle.net/gaby/Sj7y2/上的示例
如果ajax响应中有多个图像,并且您希望在加载所有图像时收到通知,则使用此略微修改的版本
$('#load').click(function(){
// inside the handler that calls the ajax
//you ajax call here
$.get('the_url_to_fetch',function(data){
// create an in-memory DOM element, and insert the ajax results
var $live = $('<div>').html(data);
// count the number of images
var imgCount = $live.find('img').length;
// apply a load method to the images in the ajax results
$('img',$live).load(function(){
// what to do for each image that is loaded
imgCount--;
if (imgCount==0)
{
// the code in here is called when all images have loaded.
}
});
// add the ajax results in the DOM
$('selector_where_to_put_the_response').html($live.children());
});
});
Run Code Online (Sandbox Code Playgroud)
http://www.jsfiddle.net/gaby/Sj7y2/1/上的示例
如果删除注释和空行,则代码不多:)所以不要被吓倒..
| 归档时间: |
|
| 查看次数: |
3355 次 |
| 最近记录: |