jQuery to check image exists if head 404 than hide it

后端 未结 2 1617
栀梦
栀梦 2020-12-29 07:48

Using php to get 100 photos url from a db and show them on a page, but some photos may no longer exist. If the photo url is fail (404) I want to use jquery to hide the image

2条回答
  •  温柔的废话
    2020-12-29 08:25

    Sending multiples ajax requests is unnecessary when you can use the onerror event.

    Check out the related jQuery/Javascript to replace broken images post.

    Adapting that to your needs:

    HTML:

    
    

    JS:

    function imgError(image){
        image.style.display = 'none';
    }
    

    Fiddle

    Or with jQuery:

    function imgError(image){
        $(image).hide();
    }
    

    I normally wouldn't use inline JS in the HTML, and even considered using an .error handler:

    $('#test img').error(function() {
        $(this).hide();
    });
    

    But the above will not work if the handler attaching is executed after the error event has fired, hence I suggest the first solution.

提交回复
热议问题