为什么在 .on() 工作时调用 .error()?(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';
});

控制台中的结果:

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

错误与此行有关:

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>

请尝试改用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');

最新更新