简体   繁体   中英

jQuery error() function not working in IE

I want to display two images that I have no idea when they will be generated. So I want to use the jquery error function to keep checking if the images exist, and display each. Following code works on every browser except IE. Why does it not work on IE, really appreciate your help.

<style type="text/css">
DIV#loader {
    width: 500px;
    height: 500px;
    overflow: hidden;
}

DIV#loader.loading {
    background: url(spinner.gif) no-repeat center center;
}
</style>


<script type="text/javascript">
$(document).ready(function() {
    var image_names = new Array(2);
    image_names[0] = 'a.jpg';
    image_names[1] = 'b.jpg';
    var divs = document.getElementsByTagName("div");
    for ( var i = 0; i < divs.length; i++) {
        showImage(image_names[i], divs[i]);
    }
});

function showImage(src, div) {
    var img = new Image();
    $(img).load(function() {
        $(this).hide();
        $(div).removeClass('loading').append(this);
        $(this).fadeIn();
    }).error(function() {
        setTimeout(function() {
            $(img).attr('src', src);
        }, 2000);
    }).attr('src', src);
}
</script>

This is the HTML body

<body>
<h1>Image Loading</h1>
<div id="loader" class="loading"></div>
<div id="loader" class="loading"></div>
</body>

It seems like IE does not know the image is generated if it does not exist when the page first loads

It's the $(document).ready({}) part; throws an error in ie for me. Changing it to $(function(){}); seems to work for me at least in IE.

Caching caused the problem. Changed the src to:

$(img).attr('src', src + "?" + (new Date().getTime()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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