Replacing Broken Images with jQuery
Having broken images displayed on a web page can be frustrating for users. Fortunately, JavaScript provides various methods to handle this issue.
One approach is to utilize jQuery's filtering capabilities to identify and replace broken images. To do this:
However, for simplicity, it's often easier to use pure JavaScript to handle broken images.
JavaScript Solution:
The onError event can be used to reassign the source attribute when an image fails to load:
function imgError(image) { image.onerror = ""; image.src = "/images/noimage.gif"; return true; }
Implement this function in the HTML:
<img src="image.png" onerror="imgError(this);"/>
Alternatively, the onError event can be handled directly in the HTML without a function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
Refer to the following table for browser compatibility with the error facility:
http://www.quirksmode.org/dom/events/error.html
The above is the detailed content of How Can I Replace Broken Images with jQuery or Plain JavaScript?. For more information, please follow other related articles on the PHP Chinese website!