在将 ajax 调用的结果插入 dom 之前,您需要定位它们。
所以为此需要使用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 响应中有多个图像,并且您希望在何时收到通知all加载其中的然后使用这个稍微修改的版本
$('#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/
如果删除注释和空行,代码就不多了:)所以不要被吓倒..