如何在IE中使用jQuery隐藏破碎的图像? [英] How to hide broken images in IE using jQuery?

查看:103
本文介绍了如何在IE中使用jQuery隐藏破碎的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试从jQuery网站复制的代码,但它在IE7 / IE8中失败,但在其他浏览器中工作。这个代码有什么问题,它来自于jQuery网站(http://api.jquery.com/error/)。我使用jQuery版本1.4.4。

I have tried this code copied from jQuery site, but it fails in IE7/IE8, but works in other browsers. What is wrong with this code, it's from jQuery site(http://api.jquery.com/error/). I'm using jQuery version 1.4.4.

$(document).ready(function(){ 
  $("img").error(function(){
    $(this).hide();     
  });    
});


推荐答案

问题是,到 $(document.ready)被执行,图像已经完成加载,所以加载/错误事件将不再被触发。

The problem is that by the time $(document.ready) is executed, the image has already finished loading so the load/error events won't be triggered anymore.

我可以想到绕过这个方法的唯一方法是重新加载图像,因此强制事件被触发:

The only way I can think of to bypass this is to reload the image, thus "force" the event to be triggered:

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

在性能上不应太糟糕,因为图像最有可能从缓存中获取,没有真正从服务器重新加载。

It shouldn't be too bad on performance as the images will be taken most probably from the cache, not really reloaded from the server.

现场测试用例(酷猫))可在这里: http://jsfiddle.net/yahavbr/QvnBC/1/

Live test case (with cool cats ;)) is available here: http://jsfiddle.net/yahavbr/QvnBC/1/

这篇关于如何在IE中使用jQuery隐藏破碎的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆