jQuery / JavaScript来替换破碎的图像 [英] jQuery/JavaScript to replace broken images

查看:290
本文介绍了jQuery / JavaScript来替换破碎的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一堆图像的网页。有时图像不可用,所以在客户端的浏览器中会显示一张破碎的图像。



如何使用jQuery获取图像集,将其过滤为破碎图片然后替换src?






- 我认为用jQuery做这件事会更容易,但它转向使用纯粹的JavaScript解决方案,也就是Prestaul提供的解决方案更容易。

解决方案处理 onError 事件让图片使用JavaScript重新分配源代码:

  function imgError(image ){
image.onerror =;
image.src =/images/noimage.gif;
返回true;





 < img src =image.pngonerror =imgError(this);/> 

或者没有JavaScript函数:

 < img src =image.pngonError =this.onerror = null; this.src ='/ images / noimage.gif'; /> 

以下兼容性表列出了支持错误工具的浏览器:



http://www.quirksmode.org/dom/events/ error.html


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 to get the set of images, filter it to broken images then replace the src?


--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.

解决方案

Handle the onError event for the image to reassign its source using JavaScript:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}

<img src="image.png" onerror="imgError(this);"/>

Or without a JavaScript function:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

The following compatibility table lists the browsers that support the error facility:

http://www.quirksmode.org/dom/events/error.html

这篇关于jQuery / JavaScript来替换破碎的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆