简体   繁体   English

为什么在.on()工作时调用.error()? (IE11)

[英]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. 如果图像无法加载,我只希望调用.error()。 This seems to be happening in IE (using 11) only. 这似乎仅在IE(使用11)中发生。

Using jquery 2.0.2 使用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. 对于IE11,似乎更改了source属性,因此出现了错误。

 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. 尝试改用load()方法。 That way you can look for errors in a callback. 这样,您可以在回调中查找错误。 This should be fired anytime the src attribute of the image is changed. 只要更改图片的src属性,就应该触发此操作。 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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