Is there a way to bind to the load() event of an i

2020-07-18 09:29发布

问题:

I have 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

回答1:

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.



回答2:

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;
});