Why did my img error function fail?

Some of the img elements that I am building dynamically can (do) fail. For these cases, I have the code I got from here: Is there a way to programmatically determine that the image link is bad? namely this:

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

... but it does not work. Warum nicht?

UPDATE

With this code inside. A separate part of the call to $ .getJSON ():

 var jObject = $('<img src=\"' + dataPoint.imghref + '\"/>'); $(jObject).error(function () { $(this).attr("src", "Content/NoImageAvailable.jpg"); }); 

... all images do not work. dataPoint.imghref contains values ​​such as:

 http://www.amazon.com/exec/obidos/ASIN/B00655KLOY/garrphotgall-20 

UPDATE 2

In nutty hell, I add "img src" like this:

 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 

... since you can see that img is being added to the DOM; perhaps the fact that i have height and width properties with my img is a problem ...

UPDATE 3

ManMohan Vyas: You mean this:

 }); //each $('#BooksContent').append(htmlBuilder). find("img").error(function(){ $(this).attr("src", "Content/NoImageAvailable.png"); }); }); //getJSON() 

?

UPDATE 4

It:

 var jObject = $(htmlBuilder); jObject.find("img").error(function () { $(this).attr("src", "Content/NoImageAvailable.png"); }); $('#BooksContent').append(jObject); 

... does not work.

And FWIW, changing this:

 $('#BooksContent').html(''); 

., $ ('# BooksContent') adds (htmlBuilder).

... to that:

$ ('# BooksContent') ReplaceWith (htmlBuilder).

... does not work (the desired material is full, but the formatting is messed up (instead of a solid black background, each section had a black background, but the general background was silver).

UPDATE 5

I just thought of something that might cause my problem: the images I'm trying to display are all jpg, but the image "Image not available" is png. Does it matter? Perhaps this is what causes the visualization engine to get confused? If so, I will just save the backup img as jpg ...

UPDATE 6

No, these last two attempts did not work either. I tried the idea of ​​Joseph Myers, then Throne, when I changed this:

 dataPoint.imghref + '\"' + ' onerror=\"imgError(this);\" target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' + dataPoint.imgsrc + '\"' + 

.. to that:

 dataPoint.imgsrc + '\" onerror=\"imgError(this);\"' + dataPoint.imgalt + '></img></a>' + 

... and no difference. I asked a little about this in the jQuery forum: I grab onto a straw here, but I wonder if there might be a problem with inappropriate versions of jQuery / jQueryUI? To support older browsers, I'm still using jQuery 1.9.1, but I'm on the edge of the bloodstream with regard to jQueryUI with version 1.10.3.

UPDATE 7

Well, here is all the relevant code (some redundant and controversial code to be reorganized was excluded to comply with SO length restrictions). (Static) CSS shouldn't matter, right? The only other “code” is Web.config and such things, so none of this should affect why I can't get reverse images to display.

Many of my unsuccessful attempts to get NoImageAvailable.png for display are commented out.

 @{ 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 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 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 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 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 ready, uncomment this: getOscars(); } } else if (ui.newTab.index() == 2) { musicContent = $('#MusicContent').html(); if (musicContent == 'Content in Music tab') { // TODO: When it 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> 

UPDATE 8

Barvaz's answer doesn't work for me either; maybe i am doing it wrong? Based on his answer, I added the following:

CSS

 .noImg { background:url(~/Content/NoImageAvailable.png); } 

JQuery

0) Added this to the finished handler:

 replaceEmptyImage = function ($img) { $img.parent().addClass('noImg'); $img.remove(); }; 

1) Changed this line:

 dataPoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" src=\"' + 

... to that:

 dataPoint.imghref + '\"' + ' target=\"_blank\"><img height=\"160\" width=\"107\" onerror=\"replaceEmptyImage($(this))\" src=\"' + 

UPDATE 9

Here is what it looks like (there is a “block” or “object” image, it's just black / empty):

enter image description here

By the way, Jamie MacFets Travel is, oddly enough, a terrific book, but perhaps especially for your children to read (any age, but maybe a pre-teen is optimal).

+6
source share
8 answers

use uploaded images plugin

https://github.com/desandro/imagesloaded

Uses jQuery pending objects. It will even help you figure out if the image is uploaded for you, so you don't need to use jQuery.error (TBH, which is actually not suitable for this).

+2
source

Although your explanation is not entirely clear, the most likely reason is that the <img> missing during the call to the $('img').error(); function $('img').error();

try

1) create a dynamic image with some id.
2) call the error function after putting the img tag in the DOM.

The <img> not associated with the error function, and this is the only reason I can see that you are not working with your code. now working sample:

HTML:

 <div id="myId"> h </div> 

jQuery Script:

 var jObject = $("<img src='helo.png' />"); $(jObject).error(function(){ $(this).attr("src", "http://rack.2.mshcdn.com/media/ZgkyMDEyLzEyLzAzL2U0L3NlZWhvd3lvdXJnLjlyMS5qcGcKcAl0aHVtYgk5NTB4NTM0IwplCWpwZw/8fec6ce4/e71/see-how-your-google-results-measure-up-with-google-grader-video--6b8bbb4b41.jpg"); }); $("#myId").html(jObject); 

you can check the working fiddle here [http://jsfiddle.net/jyXqw/] [1]

EDIT *

 var jObject = $(htmlBuilder); jObject.find("img").error(function(){ $(this).attr("src", "Content/NoImageAvailable.png"); }); $('#BooksContent').append(jObject); 

EDIT-2 * Check the script, it seems that your code is working fine: http://jsfiddle.net/jYbQx/

+6
source

Partial code update sent to me by email

This is just an assumption because all of your main scripts and JSON data are missing, so I cannot test it. However, these changes, I hope, will make it work for you. Please check them out!

Before your code says

 <div id="tabs" class="content-wrapper"> 

you should add this code exactly as written on your page (I noticed that you haven't included this in your page yet):

 <script src="//desandro.imtqy.com/imagesloaded/imagesloaded.pkgd.min.js"> </script> 

Then inside your configLoaded function you need to add a second block of code (new changes in your code are marked NEW):

 function configLoaded() { $('#lblLoading').hide(); var imgLoad = imagesLoaded('body'); /* NEW */ imgLoad.on( 'progress', function( instance, image ) { /* NEW */ var result = image.isLoaded ? 'loaded' : 'broken'; /* NEW */ image.img.src = 'Your-Placeholder-Image.png'; /* NEW */ }); /* NEW */ //$('bookDropDown').Attr('disabled', false); //$('moviesDropDown').Attr('disabled', false); //$('musicDropDown').Attr('disabled', false); } 

Thus, when your menus load new images, the progress / error handler will be reconnected (if necessary after creating new images). The most important thing, of course, is that you include the imagesloaded.pkgd.min.js script code, because the second part of the code cannot do anything without it.

Note to the author of the question

All my suggestions work in 100% of cases for me, fully tested, as well as the correct answers. Unfortunately, these solutions did not have the ability to properly integrate into your code, because I lack the complete code or stand-alone example.

In a nutshell, you gave both the JS Fiddle you provided in another question (with only one line of JavaScript there) and JS Fiddles from you and other people in different comments give me a clear picture of what your problem is. However, without enough of your actual code (ideally, all of this) I cannot show you how to turn on the solution correctly - it will be like an auto mechanic trying to install a car when the car is not there, or a math teacher trying to teach someone then mathematical problems use manual movements instead of writing with them.

I can make any of my solutions work for you, but all I need is a link to your complete code that contains the problem, or for some reason it is confidential, and then at least a self-sufficient example. See: http://sscce.org

Could you provide a link to your complete code or a self-contained example? I would be happy to change it so that it works for you. If these solutions do not work for you, then there is something else in your code that needs to be fixed, and up to this point I am providing this answer in favor of the community.

Recommended Updates

Add this script to your page:

 <script src="//desandro.imtqy.com/imagesloaded/imagesloaded.pkgd.min.js"> </script> 

That the script provides the ability to correctly detect all broken images on the page. Read about it here, including a demo that shows exactly the functionality you want to achieve for your own site: http://desandro.imtqy.com/imagesloaded/

Then add one of the following code parameters to your existing JavaScript. (You may also need to remove all other attempts to detect image loading errors from your code to make sure there are no conflicts.)

 var imgLoad = imagesLoaded('body'); imgLoad.on( 'always', function() { console.log( imgLoad.images.length + ' images loaded' ); // detect which image is broken for ( var i = 0, len = imgLoad.images.length; i < len; i++ ) { var image = imgLoad.images[i]; var result = image.isLoaded ? 'loaded' : 'broken'; console.log( 'image is ' + result + ' for ' + image.img.src ); if (result == 'broken') image.img.src = 'Your-Placeholder-Image.png'; /* CHANGE THIS */ } }); 

This code should work just as well or better, and even shorter.

 var imgLoad = imagesLoaded('body'); imgLoad.on( 'progress', function( instance, image ) { var result = image.isLoaded ? 'loaded' : 'broken'; console.log( 'image is ' + result + ' for ' + image.img.src ); image.img.src = 'Your-Placeholder-Image.png'; /* CHANGE THIS */ }); 

General observations

"In all browsers, loading, scrolling, and error events (for example, on <img>) do not bubble. In Internet Explorer 8 and below, paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the handler an event is directly related to the element that generates the event. "

http://api.jquery.com/on/

Interpretation. You cannot reliably recognize image loading errors using the jQuery selector in a document where HTML content is generated asynchronously from the jQuery command.

Therefore, when registering an error handler for an image (for example, replacing it with a “no image” image), it is important to register an error handler on the image before the image element is inserted into the DOM or becomes a fragment of a document in real time. If your src image exists in a clean JavaScript line, you need to make sure that the onerror handler onerror specified before this line is converted to a live fragment of the document. src JavaScript, - src .

, DOM . 404 Not Found , . 404, .

PNG, JPEG, .

, HTML, HTML-, jQuery img , , , HTML, onerror , script. ,

, JS Fiddle HTML, - live:

 imageError = function(it) { $(it).attr("src","placeholder.jpg"); }; htmlBuilder = htmlBuilder.replace(/<img/g, '<img onerror="imageError(this)"'); var jObject = $(htmlBuilder); $("#container").html(jObject); 

, , ( placeholder.jpg #container ), , , , , .

, ()

, onerror / error , src .

. , , , , , src .

:

fooobar.com/questions/15515/...

, , , , , , , - .

, . https://github.com/desandro/imagesloaded

, script http://desandro.imtqy.com/imagesloaded/imagesloaded.pkgd.min.js :

 var imgLoad = imagesLoaded('body'); imgLoad.on( 'always', function() { console.log( imgLoad.images.length + ' images loaded' ); // detect which image is broken for ( var i = 0, len = imgLoad.images.length; i < len; i++ ) { var image = imgLoad.images[i]; var result = image.isLoaded ? 'loaded' : 'broken'; console.log( 'image is ' + result + ' for ' + image.img.src ); if (result == 'broken') image.img.src = 'Content/NoImageAvailable.png'; /* DOUBLE CHECK THE SRC */ } }); 

, , - , , , ! :

http://jsfiddle.net/cookies/xdfjU/15/

Summary

, , :

  • , src , , HTML JavaScript. , , , 404 Not Found.
  • . ( , ) , (, , Ajax), , , hmtlBuilder , , .

( ) , "" error , , ., img , , , .

, , . JavaScript , , .

+3
source

UPDATE 5 , , .

src:

 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); 

, . .

+3
source

, , . .

+2
source

...

/

.error img. , :

 $('body').on('error', 'img', function (e) { $(e.currentTarget).attr("src", "Content/NoImageAvailable.png"); }); 

- img error . , .error .

Further...

/ HTML JS

- ; html JS. . img () .

:

 var $img = $('<img>', { 'src': dataPoint.imgsrc }); 

, :

 var $output = $('<section>', { 'class': 'wrapper' }); 

:

 $output.append($img); 

. , , , .

...

mime? ?

? , 200 ? 400? Chrome → . , .

? 200? 200 ? S3? URL- JSON - ?

+2
source

I had the same problem. .erroror other delegation methods (attached to window / document / DOM node) did not work for me on <img>dynamically created after ajax response. My solution uses an attribute onerrorinside the tag <img>(w3c standard) that calls the javascript function, removes the image and adds the noImg class to the parent node.

Inside the tag <img>:

 onerror='replaceEmptyImage($(this))' 

replaceEmptyImage:

 replaceEmptyImage = function($img) { $img.parent().addClass('noImg'); $img.remove(); }; 

In css:

 .noImg { background:url(path/to/placeholder/image); } 

See http://jsfiddle.net/tJpaR/5/

+2
source

.on('error' handler);available with jQuery 1.7error loading the image does not bubble, and the delegate does not work, linking a simple function, it works and is clean.

  function noImage(event){ $(event.target).attr('src', 'media/noImg.jpg'); } $(function (){ $('img').on('error', noImage); $("#neues_bild_button").on('click', function(ev){ var newImg = $("<img src='andersBild.jpg'/>"); newImg.on('error', noImage); $('#i2').after(newImg); }); }); 
+1
source

Source: https://habr.com/ru/post/949701/


All Articles