我正在通过ajax加载一些html,我需要一个事件来捕捉新图像加载时...
因为它在div而不是整页,我不能使用$(window).load(....
我尝试了以下但是不起作用:
$('.banners_col img:last').load(function(){.....
答案 0 :(得分:7)
在将它们插入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());
});
});
示例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());
});
});
示例http://www.jsfiddle.net/gaby/Sj7y2/1/
如果删除注释和空行,则代码不多:)所以不要被吓倒......
答案 1 :(得分:-3)
尝试使用实时函数从ajax触发html元素的事件
$('.banners_col img:last').live('change',function(){.....