如何使用jQuery在IE中隐藏损坏的图像?

new*_*bie 11 error-handling jquery image

我尝试过从jQuery网站复制的代码,但它在IE7/IE8中失败,但在其他浏览器中有效.这段代码出了什么问题,它来自jQuery网站(http://api.jquery.com/error/).我正在使用jQuery版本1.4.4.

$(document).ready(function(){ 
  $("img").error(function(){
    $(this).hide();     
  });    
});
Run Code Online (Sandbox Code Playgroud)

Sha*_*ard 13

问题是,在$(document.ready)执行时,图像已经完成加载,因此不再触发加载/错误事件.

我能想到绕过这个的唯一方法是重新加载图像,从而"强制"触发事件:

$(document).ready(function(){ 
    $("img").each(function(index) {
        $(this).error(function() {
            $(this).hide();     
        });
        $(this).attr("src", $(this).attr("src"));
  });    
});
Run Code Online (Sandbox Code Playgroud)

它的性能应该不会太差,因为图像很可能是从缓存中获取的,而不是真正从服务器重新加载.

现场测试案例(有很酷的猫;))可以在这里找到:http://jsfiddle.net/yahavbr/QvnBC/1/