Home >Web Front-end >JS Tutorial >How Can I Replace Broken Images with jQuery or JavaScript?
Replacing Broken Images with jQuery or JavaScript
Web pages often rely on images, and it's crucial to handle the situation when an image becomes unavailable and a broken image appears. This article explores two methods to address this issue: using the jQuery library and a pure JavaScript solution.
jQuery Approach
Although initially considered for this task, the jQuery approach proved less straightforward. To use jQuery for this purpose, you would need to:
Pure JavaScript Solution
An alternative approach using pure JavaScript is simpler and more efficient. By handling the onError event for the image, you can reassign its source:
function imgError(image) { image.onerror = ""; image.src = "/images/noimage.gif"; return true; }
<img src="image.png" onError="imgError(this);" />
Alternatively, you can implement this without a function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
Compatibility Considerations
It's important to note that browser support for the error facility may vary. For compatibility details, refer to the reference provided in the original answer: http://www.quirksmode.org/dom/events/error.html
The above is the detailed content of How Can I Replace Broken Images with jQuery or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!