为什么JavaScript无法加载所有图片?

时间:2018-10-14 11:02:11

标签: javascript image loading

我在下面有此代码段... 您可以看到我正在尝试加载9张图片。 当我执行以下代码时,我只会收到7次警报,并且控制台永远不会记录“所有加载的图像”。为什么会这样?

    var images = [];
    edge_topleft = new Image(); images.push(edge_topleft);
    edge_topright = new Image(); images.push(edge_topright);
    edge_bottomleft = new Image(); images.push(edge_bottomleft);
    edge_bottomright = new Image(); images.push(edge_bottomright);
    edge_cross = new Image(); images.push(edge_cross);
    block = new Image(); images.push(block);
    ice = new Image(); images.push(ice);
    way_lr = new Image(); images.push(way_lr);
    way_ud = new Image(); images.push(way_ud);


    var len = images.length;
    var counter = 0;
    [].forEach.call(images, function( img ) {
        img.addEventListener( 'load', incrementCounter, false);
    } );

    function incrementCounter() {
        counter++;
        alert(counter);
        if ( counter === len ) {
            console.log("all images loaded");
        }
    }

    edge_topleft.src = "https://dummyimage.com/10";
    edge_topright = "https://dummyimage.com/20";
    edge_bottomleft = "https://dummyimage.com/30";
    edge_bottomright.src = "https://dummyimage.com/40";
    edge_cross.src = "https://dummyimage.com/50";
    block.src = "https://dummyimage.com/60";
    ice.src = "https://dummyimage.com/70";
    way_lr.src = "https://dummyimage.com/80";
    way_ud.src = "https://dummyimage.com/90";

这是小提琴:https://jsfiddle.net/hnoaj8bg/

有人知道我在做什么错吗?

0 个答案:

没有答案