开发者

Is there a way to bind to the load() event of an image after changing it's src?

I h开发者_运维技巧ave an image <img id='my_img' src='img1.png'> and a button. Clicking the button does the following:

$('#my_img').attr('src','img2.png')

This second image (img2.png) is fairly large, and I want to know when it is fully loaded (i.e. .load() event). I tried to use .live, .bind, and .complete but none seem to fire.

Any ideas?

Thanks! Amit


I think the load event only fires once per img tag. But you can easily make a new image, and load that with a new load handler.

var img = new Image();
img.onload = function() {
  $('#my_img').attr('src', img.src);
};
img.src = 'img2.png';

Once it's loaded you can set the src of the image on your page and it will pull instantly from the browser cache.


You can do this:

$('<img id="myimg" src="1.png" /><a href="" id="clickme">click</a>').appendTo('body');

$('#clickme').click(function() {
    // replace the old img with a new one and define onLoad for the new img
    var newImg = $('<img />')
        .bind('load', function() {
            alert('2nd img loaded');
        })
        .attr('src', '2.png');
    $('#myimg').replaceWith(newImg);
    return false;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜