jQuery/JavaScript to replace broken images

后端 未结 30 2549
我寻月下人不归
我寻月下人不归 2020-11-21 05:50

I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.

How do I use jQuery

30条回答
  •  悲哀的现实
    2020-11-21 06:03

    I solved my problem with these two simple functions:

    function imgExists(imgPath) {
        var http = jQuery.ajax({
                       type:"HEAD",
                       url: imgPath,
                       async: false
                   });
        return http.status != 404;
    }
    
    function handleImageError() {
        var imgPath;
    
        $('img').each(function() {
            imgPath = $(this).attr('src');
            if (!imgExists(imgPath)) {
                $(this).attr('src', 'images/noimage.jpg');
            }
        });
    }
    

提交回复
热议问题