JavaScript replaces alt by using onerror to set the default image display

  • 2021-01-18 06:19:23
  • OfStack

JavaScript code


 // Image loading error handling 
function errorImg(img) {
img.src = " The default image .jpg";
img.onerror = null;
}

html code


<img width="32" height="32" src="1.jpg" onerror="errorImg(this)" />

For aesthetic purposes do not show cross images when web page images do not exist

When displaying on the page, 10,000 images will be moved or lost, and an image with X will be displayed on the page, which will affect the user experience. Even if the alt attribute is used to prompt "image XX", it doesn't help much.
When the image does not exist, the onerror event will be triggered. We can do the following remedial work in this event. For example:

1. Make this image element hidden:


 For aesthetic purposes do not show cross images when web page images do not exist  src=" The image url address " alt=" The picture XX" onerror="this.style.display='none'"/>

2. Replace with the default image:


 For aesthetic purposes do not show cross images when web page images do not exist  src=" The image url address " alt=" The picture XX" onerror="this.src=' Default picture url address '"/>

Note: If used improperly, it can cause an endless loop in browsers with the ES27en kernel. For example: when [the default image url address] is not successfully loaded (for example, when the network speed is relatively slow) or does not exist, it will be repeatedly loaded, finally causing a stack overflow error.

Therefore, we need to solve the problem in the following two ways:

a, change the onerror code to something else or make sure that the default image in onerror is small enough and exists.

this.onerror=null; this.onerror=null; this.onerror=null; The addition is as follows:


 For aesthetic purposes do not show cross images when web page images do not exist  src=" The image url address " alt=" The picture XX" onerror="this.src=' Default picture url address ;this.onerror=null'"/>

The above method has been tested and supported in all versions of IE, Google and Firefox.


Related articles: