开发者

Jquery check if image is loaded [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

jQuery callback on image load (even when the image is cached)

Is there a way to check if image is loaded by jquery? I have some images with external src and sometime src points to 404 page. Is there a way to check if that i开发者_开发知识库mage is loaded? and then I can remove it from dom otherwise.

Thanks.


jQuery has a function to deal with this, take a look at .error()

So for example you could attach an .error() handler to all images and display something else if there is an error, like the source no longer exists:

$('img').error(function() {
    $(this).hide();
}).attr("src", "missing.jpg");

Here is a demo


@Scoobler has the right idea, but the wrong implementation.

$(function ()
{
    $('img').error(function()
    {
        $(this).attr('src', 'http://i.stack.imgur.com/THJzu.gif');
    });
});

The .error() binding must take place on document ready - window load is too late.

Demo: http://jsfiddle.net/mattball/EebmC/


yes you can use error event like this....

$('#imageId')
  .error(function() {
    alert('Something bad happened.')
  })
  .attr("src", "image.gif");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜