admin管理员组

文章数量:1390555

I have a div

<div id='cards'>

Which I want to fill with images based on some logic. But only when images are first loaded into memory. Otherwise, through onerror I wanna fill in some text..

function pasteCard(card, to){
    if (typeof(card) == 'string')
        card = [card];
    var image = [];
    for (var i = 0; i < card.length; i++) {
        image[i] = new Image();
        image[i].src = '/sprites/open/' + card[i] + '.png';
        image[i].onload = function() {
            pasteImage(to, image[i]);
        }
        image[i].onerror = function() {            
            pasteText(to, card[i]);
            
        }
        // alert(card[i]) #1
    }

    function pasteImage(to, image) {
        to.append(image);
    }

    function pasteText(to, text) {
        // alert(card[i]) #2
        to.append(text);
    }    
}

pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));

But this isn't working.

Problem/weirdness: If only #2 alert is active it returns nothing. But strangely if #1 alert is also active it does kinda work... (but still doesn't load my images, and mostly fails too when other code is involved)

Question: Why is it not working without #1 alert (at least in that jsfiddle)

suggestions?: what should I do?

I have a div

<div id='cards'>

Which I want to fill with images based on some logic. But only when images are first loaded into memory. Otherwise, through onerror I wanna fill in some text..

function pasteCard(card, to){
    if (typeof(card) == 'string')
        card = [card];
    var image = [];
    for (var i = 0; i < card.length; i++) {
        image[i] = new Image();
        image[i].src = '/sprites/open/' + card[i] + '.png';
        image[i].onload = function() {
            pasteImage(to, image[i]);
        }
        image[i].onerror = function() {            
            pasteText(to, card[i]);
            
        }
        // alert(card[i]) #1
    }

    function pasteImage(to, image) {
        to.append(image);
    }

    function pasteText(to, text) {
        // alert(card[i]) #2
        to.append(text);
    }    
}

pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));

But this isn't working.

Problem/weirdness: If only #2 alert is active it returns nothing. But strangely if #1 alert is also active it does kinda work... (but still doesn't load my images, and mostly fails too when other code is involved)

Question: Why is it not working without #1 alert (at least in that jsfiddle)

suggestions?: what should I do?

Share Improve this question edited Jul 27, 2022 at 19:24 CommunityBot 11 silver badge asked Apr 20, 2014 at 20:14 laggingreflexlaggingreflex 34.7k36 gold badges144 silver badges200 bronze badges 1
  • 1 Your answer is in this SO answer. – Teemu Commented Apr 20, 2014 at 20:33
Add a ment  | 

3 Answers 3

Reset to default 2

Onload and onerror events are fired (executed) outside the scope of your function so your variables will be undefined. In the event method you have access to this which is the image object. You can set a data attribute to each image and access that in your error event.

Here is an example: http://jsfiddle/7CfEu/4/

The callbacks are not in the same scope as your image array is - therefor you need to declare a variable then will "connect the scopes" and use it inside the callbacks

also the i variable probably changes until the callback is fired - so by using it inside the callback you will get undefined behavior

for (var i = 0; i < card.length; i++) {
        var current_card = card[i];
        var current_image = new Image();
        current_image.onload = function() {
            pasteImage(to, current_image);
        }
        current_image.onerror = function() {
            pasteText(to, current_card);
        }
        current_image.src = '/sprites/open/' + current_card + '.png';
        image[i] = current_image;
}

Fiddle: http://jsfiddle/7CfEu/6/

(Also - closing the div tag is never a bad idea)

Just in case anyone ends up here for same reason I did.

Was going crazy because onload and onerror were not firing in the page I was building. Tried copy pasting

var myimage = new Image();
myimage.onload = function() { alert("Success"); };
myimage.onerror = function() { alert("Fail"); };
myimage.src = "mog.gif" //Doesn't exist.

Which was working within codepen and random otherwise blank pages.

Turns out the problem I was having was that I was doing AJAX requests earlier in the page. This involved authorization which in turn involved a call to

setRequestHeader();

This was resulting in a net::ERR_FILE_NOT_FOUND error instead of the expected GET mog.gif 404 (Not Found)

This seemed to prevent proper triggering of events.

Revert with

xhr.setRequestHeader("Authorization", "");

本文标签: javascriptLoading an image but onloadonerror not working as expectedStack Overflow