addEventListener to Image在chrome中不起作用

时间:2014-01-12 23:25:30

标签: javascript google-chrome

这在chrome中不起作用,但在firefox中就像魅力一样为什么会这样?我尝试了很多组合,但没有任何事件在chrome中被触发。

我已经彻底调试过了,我确实完成了所有的代码!

我正在运行Chrome版本31.0.1650.63 m

for(var x = 0; x < 2; x++)
{
    while(bFinishCheck == false)
    {
        img = new Image();


        img.addEventListener("load", function() {
            // coming soon
            alert('inside load');
        }, false);
        img.addEventListener("error", function() {
            // coming soon
            alert('inside rror');
        }, false);
        if (bCheckEnabled) {

            img.src = 'Images/Cart/' + typeOfTiles[typeCounter] + '/' + tileCounter + '.png';

            console.log(img.src);
            tileCounter++;
        }   
    }
}   
return imgArray;

2 个答案:

答案 0 :(得分:1)

它也无法使用匿名功能,但感谢您的评论,我最终这样做了。将complete属性与setInterval和Bind一起使用作为作用域。这是为了在连接之前否定缓存触发事件。很好地完成手柄!

DTE.prototype.LoadTileImages = function(typeOfTiles)
{    
    var img;
    var imgArray = new Array();
    var typeCounter = 0;

    for(var x = 0; x <= 13; x++)
    {       
        console.log("Fetching tile "+(x + 1 )+" of " + 14);
        img = new Image();
        img.src = 'Images/Cart/' + typeOfTiles[typeCounter]
                                 + '/' + (x + 1) + '.png';
        imgArray.push(img);
    }//end for loop!                        

   this.tiles = imgArray;
   setTimeout(this.InterValFunction.bind(this), 5); //Important does get called from   Global!

};

调用此函数..请参阅bind以获得正确的范围!

DTE.prototype.InterValFunction = function () {

    that = this;
    this.loadedTiles = 1;


    for (var i = 0; i < this.tiles.length; i++) {

        if (!this.tiles[i].complete) {                      
            var percentage = i * 100.0 / (this.tiles.length);
            percentage = percentage.toFixed(0).toString() + ' %';
            console.log("loading... " + percentage);
            setTimeout(this.InterValFunction.bind(this), 20);
        }
        else
        {                   
            if(this.loadedTiles == this.tiles.length) {
                console.log("loading... " + 100 +"%");
                this.DrawControlPanelTiles(this.tiles, this);
            }

            this.loadedTiles++;                             
        }
    }//End for

    this.loadedTiles = 1;
};

答案 1 :(得分:0)

在许多浏览器上(并且我不记得哪些浏览器),如果图像已经被缓存,那么甚至不会加载任何负载。

尝试添加此行:

img.src = 'Images/Cart/' + typeOfTiles[typeCounter] + '/' + tileCounter + '.png';
if (img.complete) { alert("Image complete - Image loaded from cache"); }