jQuery/JavaScript 替换损坏的图像 [英] jQuery/JavaScript to replace broken images

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

问题描述

我有一个包含一堆图像的网页.有时图像不可用,因此客户端浏览器中会显示损坏的图像.

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.

如何使用 jQuery 获取图像集,将其过滤为损坏的图像,然后替换 src?

How do I use jQuery to get the set of images, filter it to broken images then replace the src?

--我认为使用 jQuery 会更容易做到这一点,但结果证明仅使用纯 JavaScript 解决方案(即 Prestaul 提供的解决方案)要容易得多.

--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.

推荐答案

我使用内置的 error 处理程序:

I use the built in error handler:

$("img").error(function () {
    $(this).unbind("error").attr("src", "broken.gif");
});

error() 方法在 jquery 1.8 及更高版本.相反,您应该使用 .on("error") 代替:

The error() method is deprecated in jquery 1.8 and higher. Instead, you should use .on("error") instead:

$("img").on("error", function () {
    $(this).attr("src", "broken.gif");
});

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

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