在我正在处理的网站中,显示的图像并不总是(显示),因为链接可能是坏的或陈旧的(或其他).你可以在这里看到它:为什么我的动态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() {
// 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)
???
这是我的代码,它不起作用:
$.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
Run Code Online (Sandbox Code Playgroud)
......我不知道为什么......
当然是,error()方法:
$('img').error(function() {
$(this).attr("src", "imageMissing.png");
});
Run Code Online (Sandbox Code Playgroud)
错误事件将发送到文档引用并由浏览器加载的元素(如图像).如果元素未正确加载,则调用它.