jQuery/JavaScript to replace broken images

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

    Here is a quick-and-dirty way to replace all the broken images, and there is no need to change the HTML code ;)

    codepen example

        $("img").each(function(){
            var img = $(this);
            var image = new Image();
            image.src = $(img).attr("src");
            var no_image = "https://dummyimage.com/100x100/7080b5/000000&text=No+image";
            if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){
                $(img).unbind("error").attr("src", no_image).css({
                    height: $(img).css("height"),
                    width: $(img).css("width"),
                });
            }
      });
    

提交回复
热议问题