在我正在处理的网站中,显示的图像并不总是(显示),因为链接可能是坏的或陈旧的(或其他)。你可以在这里看到:为什么我的动态 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
也许类似于(伪代码):
if (ImageMissing) {
$('img').Attr('src', 'imageMissing.png');
}
?
更新
好的,所以代码应该是这样的:
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");
});
}):
}):
???
这是否会导致添加的每个图像都附加该错误处理程序,以便绑定 N 个事件处理程序,每个图像一个?
或者应该是:
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");
});
}):
???
更新 2
这是我的代码,它不起作用:
$.getJSON('Content/NBCCJr.json', function (data) {
$.each(data, function (i, dataPoint) {
if (IsYear(dataPoint.category)) {
htmlBuilder += '<div class=\"yearBanner\">' + dataPoint.category + '</div>';
} else {
htmlBuilder += '<section class=\"wrapper\" ><a id=\"mainImage\" class=\"floatLeft\" href=\"' +
dataPoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +
dataPoint.imgsrc + '\"' +
dataPoint.imgalt + '></img></a>' +
'<div id=\"prizeCategory\" class=\"category\">' +
dataPoint.category +
'</div><br/><cite id=\"prizeTitle\" >' +
dataPoint.title +
'</cite><br/><div id=\"prizeArtist\" class=\"author\">' +
dataPoint.author +
'</div><br/>';
if (dataPoint.kindle.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlize(dataPoint.kindle) + '\"' +
' target=\"_blank\">Kindle</a></button>';
}
if (dataPoint.hardbound.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlize(dataPoint.hardbound) + '\"' +
' target=\"_blank\">Hardbound</a></button>';
}
if (dataPoint.paperback.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlize(dataPoint.paperback) + '\"' +
' target=\"_blank\">Paperback</a></button>';
}
htmlBuilder += '</section>';
// Doesn't work
$('img').error(function () {
$(this).attr("src", "Content/NoImageAvailable.png");
});
}
}); //each
……我不知道为什么……