Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - jQuery / JavaScript替换损坏的图像(jQuery/JavaScript to replace broken images)

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?

(如何使用jQuery获取图像集,将其过滤为损坏的图像然后替换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.

(-我认为使用jQuery会更容易,但是事实证明,仅使用纯JavaScript解决方案(即Prestaul提供的解决方案)要容易得多。)

  ask by Dan Lord translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(处理onError事件以使图像使用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:

(或没有JavaScript函数:)

<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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...