我有一个包含一堆图像的网页.有时图像不可用,因此在客户端的浏览器中显示损坏的图像.
如何使用jQuery获取图像集,将其过滤为损坏的图像然后替换src?
- 我认为使用jQuery更容易做到这一点,但结果却更容易使用纯粹的JavaScript解决方案,即Prestaul提供的解决方案.
在我正在处理的网站中,显示的图像并不总是(显示),因为链接可能是坏的或陈旧的(或其他).你可以在这里看到它:为什么我的动态HTML似乎随机放置?
当发生这种情况时,我希望能够显示图像所在的"图像不可用"消息.那可能吗?如果是这样,需要做两件事:
1) To be able to determine programmatically that the image is not being displayed
2) To replace it, in that case, with aforementioned message
Run Code Online (Sandbox Code Playgroud)
也许像(伪代码):
if (ImageMissing) {
$('img').Attr('src', 'imageMissing.png');
}
Run Code Online (Sandbox Code Playgroud)
?
好的,所以代码应该是这样的:
function doSomething() {
var htmlBuilder = '';
$.getJSON('duckbills.json', function() {
// each ...
// process the json file, building dynamic html
htmlBuilder += 'img="bla.png"...';
$('img').error(function() {
$(this).attr("src", "imageMissing.png");
});
}):
}):
Run Code Online (Sandbox Code Playgroud)
???
这是否会导致每个图像都附加了错误处理程序,以便绑定N个事件处理程序,每个图像一个?
或者应该是:
function doSomething() {
var htmlBuilder = '';
$.getJSON('duckbills.json', function() …Run Code Online (Sandbox Code Playgroud)