Home > Article > Web Front-end > Why does my onerror image replacement code fail in Chrome and Mozilla?
The onerror attribute specifies an action to be taken when an image cannot be loaded. In this case, you have provided code to modify the src attribute and replace the faulty image with a default one.
However, you encountered an issue with this code not working in Chrome and Mozilla, despite functioning in IE.
The answer lies in the fact that modern browsers trigger the error event multiple times if the backup URL provided in the onerror handler is also invalid. This leads to an infinite loop, as the event is repeatedly fired and the src attribute continues to be modified.
To address this, you can modify your code as follows:
<img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">
By setting this.onerror=null, you prevent the error event from being triggered again. This, in turn, ensures that the image will not be replaced endlessly.
You can also refer to the live demo at http://jsfiddle.net/oLqfxjoz/ to visualize the implementation.
The above is the detailed content of Why does my onerror image replacement code fail in Chrome and Mozilla?. For more information, please follow other related articles on the PHP Chinese website!