jQuery/JavaScript to replace broken images

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

    I think I have a more elegant way with event delegation and event capturing on window's error even when the backup image fail to load.

    img {
      width: 100px;
      height: 100px;
    }
    
    error1
    error2
    avatar

    The point is :

    1. Put the code in the head and executed as the first inline script. So, it will listen the errors happen after the script.

    2. Use event capturing to catch the errors, especially for those events which don't bubble.

    3. Use event delegation which avoids binding events on each image.

    4. Give the error img element an attribute after giving them a backup.png to avoid disappearance of the backup.png and subsequent infinite loop like below:

    img error->backup.png->error->backup.png->error->,,,,,

提交回复
热议问题