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

时间:2017-08-24 16:35:48

标签: jquery internet-explorer-11

$(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';
});

控制台中的结果:

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

如果无法加载图像,我只想调用.error()。这似乎只发生在IE(使用11)中。

使用jquery 2.0.2

2 个答案:

答案 0 :(得分:0)

错误与此行有关:

thumb_img.src = ""; 

从代码中删除上一行。对于IE11,它似乎更改了源属性,因此错误。



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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

请尝试使用load()方法。这样你就可以在回调中查找错误。只要图像的src属性发生更改,就应该触发此操作。从技术上讲,你马上做的就是错误。

$('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');