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

自闭症网瘾萝莉.ら 提交于 2019-12-04 09:06:22

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;
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!