我动态构建的一些 img 元素可能(确实)失败。对于这些情况,我有一些从这里得到的代码:有没有办法以编程方式确定图像链接是坏的?即:
function getNatlBookCritics() {
var htmlBuilder = '';
// Doesn't do diddly-squat - wrong spot for it?
$('img').error(function () {
$(this).attr("src", "Content/NoImageAvailable.png");
});
$.getJSON('Content/NBCCJr.json', function (data) {
$.each(data, function (i, dataPoint) {
. . .
...但它不工作。Warum nicht?
更新
在 $.getJSON() 调用的 .each 部分中使用此代码:
var jObject = $('<img src=\"' + dataPoint.imghref + '\"/>');
$(jObject).error(function () {
$(this).attr("src", "Content/NoImageAvailable.jpg");
});
...所有图像都失败了。dataPoint.imghref 包含以下值:
http://www.amazon.com/exec/obidos/ASIN/B00655KLOY/garrphotgall-20
更新 2
在一个疯狂的地狱中,我正在添加“img src”,如下所示:
function getNatlBookCritics() {
var htmlBuilder = '';
$.getJSON('Content/nbcc.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>' +
. . .
htmlBuilder += '</section>';
}
// this is where I had the img err code
}); //each
$('#BooksContent').append(htmlBuilder);
}); //getNatlBookCritics
...所以你可以看到 img 被添加到 DOM 中;也许我的 img 具有高度和宽度属性的事实是问题所在......
更新 3
ManMohan Vyas:你的意思是这样的:
}); //each
$('#BooksContent').append(htmlBuilder).
find("img").error(function(){
$(this).attr("src", "Content/NoImageAvailable.png");
});
}); //getJSON()
?
更新 4
这个:
var jObject = $(htmlBuilder);
jObject.find("img").error(function () {
$(this).attr("src", "Content/NoImageAvailable.png");
});
$('#BooksContent').append(jObject);
……没用。
FWIW,改变了这一点:
$('#BooksContent').html('');
. . . $('#BooksContent').append(htmlBuilder);
...对此:
$('#BooksContent').replaceWith(htmlBuilder);
...效果不佳(填充了正确的内容,但格式混乱了(而不是纯黑色背景,每个部分都有黑色背景,但整体背景是银色)。
更新 5
我只是想到了可能导致我的问题的一些事情:我试图显示的图像都是 jpg,但“图像不可用”图像是 png。这有什么区别吗?这可能是导致渲染引擎感到困惑的原因吗?如果是这样,我只会将后备 img 保存为 jpg ......
更新 6
不,这最后两次尝试也没有奏效。我尝试了 Joseph Myers 的想法,然后是 Prestauls,因为我改变了这个:
dataPoint.imghref + '\"' + ' onerror=\"imgError(this);\" target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +
dataPoint.imgsrc + '\"' +
..对此:
dataPoint.imgsrc + '\" onerror=\"imgError(this);\"' +
dataPoint.imgalt + '></img></a>' +
……没有区别。不久前我在 jQuery 论坛上问过这个问题:我在这里抓住了稻草,但我想知道不匹配的 jQuery/jQueryUI 版本是否会成为问题?为了支持旧版浏览器,我仍在使用 jQuery 1.9.1,但对于 1.10.3 版的 jQueryUI,我处于“前沿”。
更新 7
好的,这里是所有相关代码(为了符合 SO 的长度限制,一些将被重构的冗余和没有实际意义的代码已被省略)。(静态)CSS 应该没关系,对吧?唯一的其他“代码”是 Web.config 和那种性质的东西,所以这些都不会影响我为什么无法显示后备图像。
我的很多让 NoImageAvailable.png 显示失败的尝试都被注释掉了。
@{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "My Next Winner";
}
<div id="tabs" class="content-wrapper">
<ul>
<li><a href="#tab-Books">Books</a></li>
<li><a href="#tab-Movies">Movies</a></li>
<li><a href="#tab-Music">Music</a></li>
</ul>
<div id="tab-Books">
<select id="bookDropDown">
<option value="Pulitzer">Pulitzer</option>
<option value="NBCC">National Book Critics Circle</option>
<option value="NBA">National Book Awards</option>
<option value="NOBA">National Outdoors Book Awards</option>
</select>
<div id="BooksContent" class="clearfix">Content in Books tab</div>
</div>
<div id="tab-Movies">
. . . . . .
<script>
$.ajaxSetup({ cache: false });
var currentBookSelection = '';
var currentMovieSelection = '';
var currentMusicSelection = '';
function imgError(image) {
image.onerror = "";
image.src = "Content/NoImageAvailable.png";
return true;
}
// BOOKS
// TODO: Refactor: just have one "getBooks()" function, passing in the name of the json file
function getNatlBookCritics() {
var htmlBuilder = '';
$.getJSON('Content/nbcc.json', function (data) {
$.each(data, function (i, dataPoint) {
if (IsYear(dataPoint.category)) {
htmlBuilder += '<div class=\"yearBanner\">' + dataPoint.category + '</div>';
} else { // see snippet at top of unit for dealing with landscape-oriented books (such as some children's books) to change height and width of img
htmlBuilder += '<section class=\"wrapper\" ><a id=\"mainImage\" class=\"floatLeft\" href=\"' +
dataPoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +
//dataPoint.imghref + '\"' + ' onerror=\"imgError(this);\" target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +
//dataPoint.imgsrc + '\" onerror=\"imgError(this);\"' +
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=\"' + Urlify(dataPoint.kindle) + '\"' +
' target=\"_blank\">Kindle</a></button>';
}
if (dataPoint.paperback.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.paperback) + '\"' +
' target=\"_blank\">Paperback</a></button>';
}
if (dataPoint.hardbound.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.hardbound) + '\"' +
' target=\"_blank\">Hardcover</a></button>';
}
htmlBuilder += '</section>';
//// Doesn't work
//$('img').error(function () {
// $(this).attr("src", "Content/NoImageAvailable.png");
//});
// When get answer, try this: <-- they all fail with this
//var jObject = $('<img src=\"' + dataPoint.imghref + '\"/>');
//var jObject = $('<img src=' + dataPoint.imghref + ' />');
//$(jObject).error(function () {
// $(this).attr("src", "Content/NoImageAvailable.jpg");
//});
}
}); //each
//var jObject = $(htmlBuilder).find('img').error(function () {
// $(this).attr("src", "Content/NoImageAvailable.png")
//});
//$("#BooksContent").html(jObject);
//var jObject = $(htmlBuilder);
//jObject.find("img").error(function () {
// $(this).attr("src", "Content/NoImageAvailable.png");
//});
//$('#BooksContent').append(jObject);
// 7/23
//imageError = function (it) {
// $(it).attr("src", "Content/NoImageAvailable.png");
//};
//htmlBuilder = htmlBuilder.replace(/<img/g, '<img onerror="imageError(this)"');
//var jObject = $(htmlBuilder);
//$("#BooksContent").html(jObject);
// </ 7/23
//$('#BooksContent').html('');
//$('#BooksContent').append(htmlBuilder);
////try this 7/24/2013
//var $jObject = $('<img>');
//$jObject.error(function () { //$jObject is already a jquery object, don't wrap it again
// $(this).attr("src", "Content/NoImageAvailable.jpg");
//}).attr('src', dataPoint.imghref);
//</try this 7/24/2013
//$('#BooksContent').html(htmlBuilder);
$('#BooksContent').html(htmlBuilder).
find('img, button').click(function (evt) {
$(this).css('border', '1px solid red')
//evt.preventDefault();
//find('img').error(function() {
// this.src = "/Content/NoImageAvailable.png"
//})
});
//$('#BooksContent').replaceWith(htmlBuilder);
//.find('img').error(function() {
// this.src = "Content/NoImageAvailable.png"
// //this.src = "http://www.gravatar.com/avatar/317f4b62da2b0186feac9b6209793505?s=80&d=http%3A%2F%2Fimg.zohostatic.com%2Fdiscussions%2Fv1%2Fimages%2FdefaultPhoto.png";
//});
$('#BooksContent').css('background-color', 'black');
$('button').button();
}); //getJSONnbcc
$largest = 0;
$(".wrapper").each(function () {
if ($(this).height() > $largest) {
$largest = $(this).height();
}
});
$(".wrapper").css("height", $largest);
} // getNatlBookCritics()
function getPulitzers() {
// Since pulitzers will be the one that shows when site first opens, added rel="nofollow"
// in each href; in this way only this method differs from the other "getX" book methods
var htmlBuilder = '';
$.getJSON('Content/pulitzers2.json', function (data) {
$.each(data, function (i, dataPoint) {
if (IsYear(dataPoint.category)) {
htmlBuilder += '<div class=\"yearBanner\">' + dataPoint.category + '</div>';
} else { // see snippet at top of unit for dealing with landscape-oriented books (such as some children's books) to change height and width of img
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=\"' + Urlify(dataPoint.kindle) + '\"' +
' target=\"_blank\" rel=\"nofollow\" >Kindle</a></button>';
}
if (dataPoint.hardbound.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.hardbound) + '\"' +
' target=\"_blank\" rel=\"nofollow\" >Hardcover</a></button>';
}
if (dataPoint.paperback.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.paperback) + '\"' +
' target=\"_blank\" rel=\"nofollow\" >Paperback</a></button>';
}
htmlBuilder += '</section>';
}
}); //each
$('#BooksContent').html(htmlBuilder).
find('img, button').click(function (evt) {
$(this).css('border', '1px solid red')
});
$('#BooksContent').css('background-color', 'black');
$('button').button();
}); //getPulitzers
$largest = 0;
$(".wrapper").each(function () {
if ($(this).height() > $largest) {
$largest = $(this).height();
}
});
$(".wrapper").css("height", $largest);
// This is not working; axed a question on the jQuery forum
$('img, button').click(function (evt) {
$(this).css('border', '5px solid green');
evt.preventDefault();
});
// added this 7/24/2013 - does nothing
//$(function () {
// $('a').click(function () {
// open(this.href, 'NewWin', 'toolbar=yes');
// self.focus();
// return false;
// });
//});
} // getPulitzers()
function getNatlBook() {
. . . } // getNatlBook()
function getNOBA() {
// load bookContents using getJSON
}
// MOVIES
// Movies differ from books and music in that some of the awards do not always have a person as winner - just the movie
// So we have to check for that and conditionally add that bit of html (what corresponds to author in books and
// artist in music)
function getMovies(pathToJsonFile) {
var htmlBuilder = '';
$.getJSON(pathToJsonFile, function (data) {
// I tried renaming the above to nbcc.json, but it won't work with that name...?!? $.getJSON('Content/nbcc.json', function (data) {
$.each(data, function (i, dataPoint) {
if (IsYear(dataPoint.category)) {
htmlBuilder += '<div class=\"yearBanner\">' + dataPoint.category + '</div>';
} else { // see snippet at top of unit for dealing with landscape-oriented books (such as some children's books) to change height and width of img
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.film +
'</cite><br/>';
if (dataPoint.person.trim().length > 2) {
htmlBuilder += '<div id=\"prizeArtist\" class=\"person\">' + dataPoint.person + '</div><br/>';
}
if (dataPoint.bluray.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.bluray) + '\"' +
' target=\"_blank\" >BluRay</a></button>';
}
if (dataPoint.dvd.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.dvd) + '\"' +
' target=\"_blank\" >DVD</a></button>';
}
htmlBuilder += '</section>';
}
}); //each
$('#MoviesContent').html(htmlBuilder).
find('img, button').click(function (evt) {
$(this).css('border', '1px solid silver')
});
$('#MoviesContent').css('background-color', 'black');
$('button').button();
//console.log(htmlBuilder); <-- may want this for response to click on tab when movie tab is selected
}); //getOscars
$largest = 0;
$(".wrapper").each(function () {
if ($(this).height() > $largest) {
$largest = $(this).height();
}
});
$(".wrapper").css("height", $largest);
}
// MUSIC
// "work" is used for "album or song or recording or performance"
//TODO: Make this a generic "Music" function a la Movies above
function getGrammies() {
var htmlBuilder = '';
$.getJSON('Content/grammies.json', function (data) {
$.each(data, function (i, dataPoint) {
if (IsYear(dataPoint.category)) {
htmlBuilder += '<div class=\"yearBanner\">' + dataPoint.category + '</div>';
} else { // see snippet at top of unit for dealing with landscape-oriented books (such as some children's books) to change height and width of img
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.work +
'</cite><br/><div id=\"prizeArtist\" class=\"work\">' +
dataPoint.artist +
'</div><br/>';
if (dataPoint.mp3.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.mp3) + '\"' +
' target=\"_blank\">mp3</a></button>';
}
if (dataPoint.dvd.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.dvd) + '\"' +
' target=\"_blank\">DVD</a></button>';
}
if (dataPoint.vinyl.trim().length > 2) {
htmlBuilder += '<button><a href=\"' + Urlify(dataPoint.vinyl) + '\"' +
' target=\"_blank\">Vinyl</a></button>';
}
htmlBuilder += '</section>';
//// Doesn't work
//$('img').error(function () {
// $(this).attr("src", "Content/NoImageAvailable.png");
//});
}
}); //each
$('#MusicContent').html(htmlBuilder).
find('img, button').click(function (evt) {
$(this).css('border', '1px solid gold')
});
$('#MusicContent').css('background-color', 'black');
$('button').button();
}); //getJSONMusic
$largest = 0;
$(".wrapper").each(function () {
if ($(this).height() > $largest) {
$largest = $(this).height();
}
});
$(".wrapper").css("height", $largest);
}
function configLoading() {
$('#lblLoading').show();
// TODO: Not working for some reason - the configLoaded never sets them back to enabled...
//$('bookDropDown').Attr('disabled', true);
//$('moviesDropDown').Attr('disabled', true);
//$('musicDropDown').Attr('disabled', true);
}
function configLoaded() {
$('#lblLoading').hide();
//$('bookDropDown').Attr('disabled', false);
//$('moviesDropDown').Attr('disabled', false);
//$('musicDropDown').Attr('disabled', false);
}
$(document).ready(function () {
$('#tabs').tabs({
beforeActivate: function (event, ui) {
// Pulitzers is loaded at first; any time the books tab is clicked, something will already be there
if (ui.newTab.index() == 1) {
moviesContent = $('#MoviesContent').html();
if (moviesContent == 'Content in Movies tab') {
// TODO: When it's ready, uncomment this: getOscars();
}
}
else if (ui.newTab.index() == 2) {
musicContent = $('#MusicContent').html();
if (musicContent == 'Content in Music tab') {
// TODO: When it's ready, uncomment this: getGrammies();
}
}
}
});
$('body').on('error', 'img', function (e) {
$(e.currentTarget).attr("src", "Content/NoImageAvailable.png");
});
// This makes the external hrefs / targets "pop up"; I don't think I want that...
//$('body').on('click', 'a', function () {
// open(this.href, 'NewWin', 'toolbar=yes')
// self.focus();
// return false;
//});
// Books tab is default view; load the default list (Pulitzer); the other two default lists (oscars and grammies)
// will load the first time the user selects the corresponding tab (see beforeActivate() above)
getPulitzers();
currentBookSelection = "Pulitzer";
configLoaded();
$('#bookDropDown').change(function () {
// TODO: May want to keep track of when in loading mode, and if so, exit/return
configLoading();
$('#body').removeClass('bronzeBackground silverBackground goldBackground').addClass('bronzeBackground');
var sel = this.value;
if ((sel == "NBCC") && (currentBookSelection != "NBCC")) {
getNatlBookCritics();
currentBookSelection = "NBCC";
}
else if ((sel == "NBA") && (currentBookSelection != "NBA")) {
getNatlBook();
currentBookSelection = "NBA";
}
else if ((sel == "NOBA") && (currentBookSelection != "NOBA")) {
getNOBA();
currentBookSelection = "NOBA";
}
else if ((sel == "Pulitzer") && (currentBookSelection != "Pulitzer")) {
getPulitzers();
currentBookSelection = "Pulitzer";
}
configLoaded();
}); //bookDropDown
$('#moviesDropDown').change(function () {
configLoading();
$('#body').removeClass('bronzeBackground silverBackground goldBackground').addClass('silverBackground');
var sel = this.value;
if ((sel == "Oscars") && (currentMovieSelection != "Oscars")) {
currentMovieSelection = "Oscars";
getMovies('Content/oscars.json');
}
else if ((sel == "GoldenGlobe") && (currentMovieSelection != "GoldenGlobe")) {
currentMovieSelection = "GoldenGlobe";
getMovies('Content/goldenglobe.json');
}
else if ((sel == "Cannes") && (currentMovieSelection != "Cannes")) {
currentMovieSelection = "Cannes";
getMovies('Content/cannes.json');
}
else if ((sel == "Sundance") && (currentMovieSelection != "Sundance")) {
currentMovieSelection = "Sundance";
getMovies('Content/sundance.json');
}
configLoaded();
}); //moviesDropDown
$('#musicDropDown').change(function () {
configLoading();
$('#body').removeClass('bronzeBackground silverBackground goldBackground').addClass('goldBackground');
var sel = this.value;
if ((sel == "Grammies") && (currentMusicSelection != "Grammies")) {
currentMusicSelection = "Grammies";
getGrammies();
}
else if ((sel == "AMA") && (currentMusicSelection != "AMA")) {
currentMusicSelection = "AMA";
getAMA();
}
else if ((sel == "CMA") && (currentMusicSelection != "CMA")) {
currentMusicSelection = "CMA";
getCMA();
}
else if ((sel == "Indies") && (currentMusicSelection != "Indies")) {
currentMusicSelection = "Indies";
getIndies();
}
configLoaded();
}); //musicDropDown
// added 7/24/2013, changed nothing
//$(function() {
// $('a').click(function() {
// open(this.href, 'NewWin', 'toolbar=yes');
// self.focus();
// return false;
// });
//});
}); //ready
</script>
更新 8
barvaz 的回答对我也不起作用;也许我做错了?根据他的回答,这是我添加的:
CSS
.noImg {
background:url(~/Content/NoImageAvailable.png);
}
jQuery
0)在准备好的处理程序中添加了这个:
replaceEmptyImage = function ($img) {
$img.parent().addClass('noImg');
$img.remove();
};
1)改变了这一行:
dataPoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' +
...对此:
dataPoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" onerror=\"replaceEmptyImage($(this))\" src=\"' +
更新 9
这是它的样子(图像“块”或“对象”在那里,只是它是黑色/空白):
顺便说一句,杰米麦克菲特斯的游记无论如何都是一本很棒的书,但也许特别适合给你的孩子读(任何年龄,但也许青少年时期是最佳的)。