简体   繁体   中英

Why is .error() being called when .on() is working? (IE11)

$(function() {  /*jquery .ready()*/
  var thumb_img = new Image();
  thumb_img.id = 'cid_' + 1730;
  thumb_img.src = ""; 

  $(thumb_img).on('load', function() {
    console.log("Image loaded " + thumb_img.src);
  }).error(function(){
    console.log("ERROR loading image " + thumb_img.src);
  });

  thumb_img.src = 'https://fiddle.jshell.net/img/logo.png';
});

Result in console:

Image loaded https://fiddle.jshell.net/img/logo.png
ERROR loading image https://fiddle.jshell.net/img/logo.png

I only want .error() to be called if the image cannot be loaded. This seems to be happening in IE (using 11) only.

Using jquery 2.0.2

The error is related to this line:

thumb_img.src = ""; 

Remove the previous line from your code. For IE11 it seems like changing the source attribute and so the error.

 var thumb_img = new Image(); thumb_img.id = 'cid_' + 1730; //thumb_img.src = ""; $(thumb_img).on('load', function() { console.log("Image loaded " + thumb_img.src); }).on('error', function(e){ alert("ERROR loading image " + thumb_img.src); }); thumb_img.src ='https://fiddle.jshell.net/img/logo.png'; document.body.appendChild(thumb_img); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> 

Try using the load() method instead. That way you can look for errors in a callback. This should be fired anytime the src attribute of the image is changed. Which technically you are doing right away, hence the error.

$('img').load(function(response, status, xhr){
    console.log('loaded');
    console.log({response,status, xhr});
    if (status === "error") {
        console.log('error here');
    }
});

$('img').attr('src', 'someimageurl');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM