jQuery/JavaScript to replace broken images

后端 未结 30 2500
我寻月下人不归
我寻月下人不归 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:28

    By using Prestaul's answer, I added some checks and I prefer to use the jQuery way.

    
    
    
    function imgError(image, type) {
        if (typeof jQuery !== 'undefined') {
           var imgWidth=$(image).attr("width");
           var imgHeight=$(image).attr("height");
    
            // Type 1 puts a placeholder image
            // Type 2 hides img tag
            if (type == 1) {
                if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {
                    $(image).attr("src", "http://lorempixel.com/" + imgWidth + "/" + imgHeight + "/");
                } else {
                   $(image).attr("src", "http://lorempixel.com/200/200/");
                }
            } else if (type == 2) {
                $(image).hide();
            }
        }
        return true;
    }
    

提交回复
热议问题